project
stringclasses
788 values
commit_id
stringlengths
6
81
CVE ID
stringlengths
13
16
CWE ID
stringclasses
126 values
func
stringlengths
14
482k
vul
int8
0
1
audiofile
2bbebc4aa0c847d59f42e291d99ad015e40c51c7
NOT_APPLICABLE
NOT_APPLICABLE
Module *G711::createCompress(_Track *track, AFvirtualfile *fh, bool canSeek, bool headerless, AFframecount *chunkframes) { return new G711(Compress, track, fh, canSeek); }
0
file
1aec04dbf8a24b8a6ba64c4f74efa0628e36db0b
NOT_APPLICABLE
NOT_APPLICABLE
cdf_read_ssat(const cdf_info_t *info, const cdf_header_t *h, const cdf_sat_t *sat, cdf_sat_t *ssat) { size_t i, j; size_t ss = CDF_SEC_SIZE(h); cdf_secid_t sid = h->h_secid_first_sector_in_short_sat; ssat->sat_len = cdf_count_chain(sat, sid, CDF_SEC_SIZE(h)); if (ssat->sat_len == (size_t)-1) return -1; ssat->sat_tab = CAST(cdf_secid_t *, calloc(ssat->sat_len, ss)); if (ssat->sat_tab == NULL) return -1; for (j = i = 0; sid >= 0; i++, j++) { if (j >= CDF_LOOP_LIMIT) { DPRINTF(("Read short sat sector loop limit")); errno = EFTYPE; goto out; } if (i >= ssat->sat_len) { DPRINTF(("Out of bounds reading short sector chain " "%" SIZE_T_FORMAT "u > %" SIZE_T_FORMAT "u\n", i, ssat->sat_len)); errno = EFTYPE; goto out; } if (cdf_read_sector(info, ssat->sat_tab, i * ss, ss, h, sid) != (ssize_t)ss) { DPRINTF(("Reading short sat sector %d", sid)); goto out; } sid = CDF_TOLE4((uint32_t)sat->sat_tab[sid]); } return 0; out: free(ssat->sat_tab); return -1; }
0
linux-2.6
9926e4c74300c4b31dee007298c6475d33369df0
NOT_APPLICABLE
NOT_APPLICABLE
asmlinkage long sys_setregid(gid_t rgid, gid_t egid) { int old_rgid = current->gid; int old_egid = current->egid; int new_rgid = old_rgid; int new_egid = old_egid; int retval; retval = security_task_setgid(rgid, egid, (gid_t)-1, LSM_SETID_RE); if (retval) return retval; if (rgid != (gid_t) -1) { if ((old_rgid == rgid) || (current->egid==rgid) || capable(CAP_SETGID)) new_rgid = rgid; else return -EPERM; } if (egid != (gid_t) -1) { if ((old_rgid == egid) || (current->egid == egid) || (current->sgid == egid) || capable(CAP_SETGID)) new_egid = egid; else return -EPERM; } if (new_egid != old_egid) { current->mm->dumpable = suid_dumpable; smp_wmb(); } if (rgid != (gid_t) -1 || (egid != (gid_t) -1 && egid != old_rgid)) current->sgid = new_egid; current->fsgid = new_egid; current->egid = new_egid; current->gid = new_rgid; key_fsgid_changed(current); proc_id_connector(current, PROC_EVENT_GID); return 0; }
0
Chrome
2440e872debd68ae7c2a8bf9ddb34df2cce378cd
NOT_APPLICABLE
NOT_APPLICABLE
HRESULT CGaiaCredentialBase::SaveAccountInfo( const base::DictionaryValue& properties) { LOGFN(INFO); base::string16 sid = GetDictString(&properties, kKeySID); if (sid.empty()) { LOGFN(ERROR) << "SID is empty"; return E_INVALIDARG; } base::string16 username = GetDictString(&properties, kKeyUsername); if (username.empty()) { LOGFN(ERROR) << "Username is empty"; return E_INVALIDARG; } base::string16 password = GetDictString(&properties, kKeyPassword); if (password.empty()) { LOGFN(ERROR) << "Password is empty"; return E_INVALIDARG; } base::string16 domain = GetDictString(&properties, kKeyDomain); auto profile = ScopedUserProfile::Create(sid, domain, username, password); if (!profile) { LOGFN(ERROR) << "Could not load user profile"; return E_UNEXPECTED; } HRESULT hr = profile->SaveAccountInfo(properties); if (FAILED(hr)) LOGFN(ERROR) << "profile.SaveAccountInfo failed (cont) hr=" << putHR(hr); return hr; }
0
ImageMagick
f6463ca9588579633bbaed9460899d892aa3c64a
NOT_APPLICABLE
NOT_APPLICABLE
static boolean ReadIPTCProfile(j_decompress_ptr jpeg_info) { char magick[MagickPathExtent]; ErrorManager *error_manager; ExceptionInfo *exception; Image *image; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t length; StringInfo *iptc_profile, *profile; /* Determine length of binary data stored here. */ length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8); length+=(size_t) GetCharacter(jpeg_info); length-=2; if (length <= 14) { while (length-- > 0) (void) GetCharacter(jpeg_info); return(TRUE); } /* Validate that this was written as a Photoshop resource format slug. */ for (i=0; i < 10; i++) magick[i]=(char) GetCharacter(jpeg_info); magick[10]='\0'; length-=10; if (length <= 10) return(TRUE); if (LocaleCompare(magick,"Photoshop ") != 0) { /* Not a IPTC profile, return. */ for (i=0; i < (ssize_t) length; i++) (void) GetCharacter(jpeg_info); return(TRUE); } /* Remove the version number. */ for (i=0; i < 4; i++) (void) GetCharacter(jpeg_info); if (length <= 11) return(TRUE); length-=4; error_manager=(ErrorManager *) jpeg_info->client_data; exception=error_manager->exception; image=error_manager->image; profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } error_manager->profile=profile; p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) *p++=(unsigned char) GetCharacter(jpeg_info); error_manager->profile=NULL; iptc_profile=(StringInfo *) GetImageProfile(image,"8bim"); if (iptc_profile != (StringInfo *) NULL) { ConcatenateStringInfo(iptc_profile,profile); profile=DestroyStringInfo(profile); } else { status=SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: iptc, %.20g bytes",(double) length); return(TRUE); }
0
linux
e4f3aa2e1e67bb48dfbaaf1cad59013d5a5bc276
NOT_APPLICABLE
NOT_APPLICABLE
static void cdrom_update_settings(void) { struct cdrom_device_info *cdi; mutex_lock(&cdrom_mutex); list_for_each_entry(cdi, &cdrom_list, list) { if (autoclose && CDROM_CAN(CDC_CLOSE_TRAY)) cdi->options |= CDO_AUTO_CLOSE; else if (!autoclose) cdi->options &= ~CDO_AUTO_CLOSE; if (autoeject && CDROM_CAN(CDC_OPEN_TRAY)) cdi->options |= CDO_AUTO_EJECT; else if (!autoeject) cdi->options &= ~CDO_AUTO_EJECT; if (lockdoor && CDROM_CAN(CDC_LOCK)) cdi->options |= CDO_LOCK; else if (!lockdoor) cdi->options &= ~CDO_LOCK; if (check_media_type) cdi->options |= CDO_CHECK_TYPE; else cdi->options &= ~CDO_CHECK_TYPE; } mutex_unlock(&cdrom_mutex); }
0
linux
2f95fa5c955d0a9987ffdc3a095e2f4e62c5f2a9
NOT_APPLICABLE
NOT_APPLICABLE
*/ static unsigned int bfq_update_depths(struct bfq_data *bfqd, struct sbitmap_queue *bt) { unsigned int i, j, min_shallow = UINT_MAX; /* * In-word depths if no bfq_queue is being weight-raised: * leaving 25% of tags only for sync reads. * * In next formulas, right-shift the value * (1U<<bt->sb.shift), instead of computing directly * (1U<<(bt->sb.shift - something)), to be robust against * any possible value of bt->sb.shift, without having to * limit 'something'. */ /* no more than 50% of tags for async I/O */ bfqd->word_depths[0][0] = max((1U << bt->sb.shift) >> 1, 1U); /* * no more than 75% of tags for sync writes (25% extra tags * w.r.t. async I/O, to prevent async I/O from starving sync * writes) */ bfqd->word_depths[0][1] = max(((1U << bt->sb.shift) * 3) >> 2, 1U); /* * In-word depths in case some bfq_queue is being weight- * raised: leaving ~63% of tags for sync reads. This is the * highest percentage for which, in our tests, application * start-up times didn't suffer from any regression due to tag * shortage. */ /* no more than ~18% of tags for async I/O */ bfqd->word_depths[1][0] = max(((1U << bt->sb.shift) * 3) >> 4, 1U); /* no more than ~37% of tags for sync writes (~20% extra tags) */ bfqd->word_depths[1][1] = max(((1U << bt->sb.shift) * 6) >> 4, 1U); for (i = 0; i < 2; i++) for (j = 0; j < 2; j++) min_shallow = min(min_shallow, bfqd->word_depths[i][j]); return min_shallow;
0
Chrome
6b5f83842b5edb5d4bd6684b196b3630c6769731
NOT_APPLICABLE
NOT_APPLICABLE
const Extension* ExtensionSettingsHandler::GetExtension(const ListValue* args) { std::string extension_id = UTF16ToUTF8(ExtractStringValue(args)); CHECK(!extension_id.empty()); return extension_service_->GetExtensionById(extension_id, true); }
0
tip
511885d7061eda3eb1faf3f57dcc936ff75863f1
NOT_APPLICABLE
NOT_APPLICABLE
bool timerqueue_del(struct timerqueue_head *head, struct timerqueue_node *node) { WARN_ON_ONCE(RB_EMPTY_NODE(&node->node)); rb_erase_cached(&node->node, &head->rb_root); RB_CLEAR_NODE(&node->node); return !RB_EMPTY_ROOT(&head->rb_root.rb_root); }
0
uriparser
864f5d4c127def386dd5cc926ad96934b297f04e
NOT_APPLICABLE
NOT_APPLICABLE
bool testNormalizeSyntaxHelper(const wchar_t * uriText, const wchar_t * expectedNormalized, unsigned int mask = static_cast<unsigned int>(-1)) { UriParserStateW stateW; int res; UriUriW testUri; stateW.uri = &testUri; res = uriParseUriW(&stateW, uriText); if (res != 0) { uriFreeUriMembersW(&testUri); return false; } UriUriW expectedUri; stateW.uri = &expectedUri; res = uriParseUriW(&stateW, expectedNormalized); if (res != 0) { uriFreeUriMembersW(&testUri); uriFreeUriMembersW(&expectedUri); return false; } res = uriNormalizeSyntaxExW(&testUri, mask); if (res != 0) { uriFreeUriMembersW(&testUri); uriFreeUriMembersW(&expectedUri); return false; } bool equalAfter = (URI_TRUE == uriEqualsUriW(&testUri, &expectedUri)); res = uriNormalizeSyntaxExW(&testUri, mask); if (res != 0) { uriFreeUriMembersW(&testUri); uriFreeUriMembersW(&expectedUri); return false; } equalAfter = equalAfter && (URI_TRUE == uriEqualsUriW(&testUri, &expectedUri)); uriFreeUriMembersW(&testUri); uriFreeUriMembersW(&expectedUri); return equalAfter; }
0
libde265
697aa4f7c774abd6374596e6707a6f4f54265355
NOT_APPLICABLE
NOT_APPLICABLE
bool PBMotion::operator==(const PBMotion& b) const { const PBMotion& a = *this; // TODO: is this really correct? no check for predFlag? Standard says so... (p.127) for (int i=0;i<2;i++) { if (a.predFlag[i] != b.predFlag[i]) return false; if (a.predFlag[i]) { if (a.mv[i].x != b.mv[i].x) return false; if (a.mv[i].y != b.mv[i].y) return false; if (a.refIdx[i] != b.refIdx[i]) return false; } } return true; }
0
Chrome
4c8b008f055f79e622344627fed7f820375a4f01
NOT_APPLICABLE
NOT_APPLICABLE
bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState) { unsigned length = qualifiedName.length(); if (!length) { exceptionState.throwDOMException(InvalidCharacterError, "The qualified name provided is empty."); return false; } ParseQualifiedNameResult returnValue; if (qualifiedName.is8Bit()) returnValue = parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName); else returnValue = parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName); if (returnValue.status == QNValid) return true; StringBuilder message; message.appendLiteral("The qualified name provided ('"); message.append(qualifiedName); message.appendLiteral("') "); if (returnValue.status == QNMultipleColons) { message.appendLiteral("contains multiple colons."); } else if (returnValue.status == QNInvalidStartChar) { message.appendLiteral("contains the invalid name-start character '"); message.append(returnValue.character); message.appendLiteral("'."); } else if (returnValue.status == QNInvalidChar) { message.appendLiteral("contains the invalid character '"); message.append(returnValue.character); message.appendLiteral("'."); } else if (returnValue.status == QNEmptyPrefix) { message.appendLiteral("has an empty namespace prefix."); } else { ASSERT(returnValue.status == QNEmptyLocalName); message.appendLiteral("has an empty local name."); } if (returnValue.status == QNInvalidStartChar || returnValue.status == QNInvalidChar) exceptionState.throwDOMException(InvalidCharacterError, message.toString()); else exceptionState.throwDOMException(NamespaceError, message.toString()); return false; }
0
savannah
7a42b78be9a4108d98833069a88e6fddb9285008
NOT_APPLICABLE
NOT_APPLICABLE
aspath_print (struct aspath *as) { return (as ? as->str : NULL); }
0
crawl
768f60da87a3fa0b5561da5ade9309577c176d04
NOT_APPLICABLE
NOT_APPLICABLE
void CLua::setglobal(const char *name) { lua_setglobal(state(), name); }
0
tmux
2ffbd5b5f05dded1564ba32a6a00b0b417439b2f
NOT_APPLICABLE
NOT_APPLICABLE
input_parse(struct window_pane *wp) { struct input_ctx *ictx = wp->ictx; const struct input_transition *itr; struct evbuffer *evb = wp->event->input; u_char *buf; size_t len, off; if (EVBUFFER_LENGTH(evb) == 0) return; wp->window->flags |= WINDOW_ACTIVITY; wp->window->flags &= ~WINDOW_SILENCE; if (gettimeofday(&wp->window->activity_time, NULL) != 0) fatal("gettimeofday failed"); /* * Open the screen. Use NULL wp if there is a mode set as don't want to * update the tty. */ if (wp->mode == NULL) screen_write_start(&ictx->ctx, wp, &wp->base); else screen_write_start(&ictx->ctx, NULL, &wp->base); ictx->wp = wp; buf = EVBUFFER_DATA(evb); len = EVBUFFER_LENGTH(evb); notify_input(wp, evb); off = 0; /* Parse the input. */ while (off < len) { ictx->ch = buf[off++]; log_debug("%s: '%c' %s", __func__, ictx->ch, ictx->state->name); /* Find the transition. */ itr = ictx->state->transitions; while (itr->first != -1 && itr->last != -1) { if (ictx->ch >= itr->first && ictx->ch <= itr->last) break; itr++; } if (itr->first == -1 || itr->last == -1) { /* No transition? Eh? */ fatalx("No transition from state!"); } /* * Execute the handler, if any. Don't switch state if it * returns non-zero. */ if (itr->handler != NULL && itr->handler(ictx) != 0) continue; /* And switch state, if necessary. */ if (itr->state != NULL) input_set_state(wp, itr); /* If not in ground state, save input. */ if (ictx->state != &input_state_ground) evbuffer_add(ictx->since_ground, &ictx->ch, 1); } /* Close the screen. */ screen_write_stop(&ictx->ctx); evbuffer_drain(evb, len); }
0
mongo
ee97c0699fd55b498310996ee002328e533681a3
NOT_APPLICABLE
NOT_APPLICABLE
TEST_F(QueryPlannerTest, IntersectSubtreeAndPred) { params.options = QueryPlannerParams::NO_TABLE_SCAN | QueryPlannerParams::INDEX_INTERSECTION; addIndex(BSON("a" << 1)); addIndex(BSON("b" << 1)); addIndex(BSON("c" << 1)); runQuery(fromjson("{a: 1, $or: [{b:1}, {c:1}]}")); // This (can be) rewritten to $or:[ {a:1, b:1}, {c:1, d:1}]. We don't look for the various // single $or solutions as that's tested elsewhere. We look for the intersect solution, // where each AND inside of the root OR is an and_sorted. size_t matches = 0; matches += numSolutionMatches( "{fetch: {filter: {a:1,$or:[{b:1},{c:1}]}, node: {or: {nodes: [" "{andSorted: {nodes: [" "{ixscan: {filter: null, pattern: {'a':1}}}," "{ixscan: {filter: null, pattern: {'b':1}}}]}}," "{andSorted: {nodes: [" "{ixscan: {filter: null, pattern: {'a':1}}}," "{ixscan: {filter: null, pattern: {'c':1}}}]}}]}}}}"); matches += numSolutionMatches( "{fetch: {filter: {a:1,$or:[{b:1},{c:1}]}, node: {andHash: {nodes:[" "{or: {nodes: [{ixscan:{filter:null, pattern:{b:1}}}," "{ixscan:{filter:null, pattern:{c:1}}}]}}," "{ixscan:{filter: null, pattern:{a:1}}}]}}}}"); ASSERT_GREATER_THAN_OR_EQUALS(matches, 1U); }
0
xterm-snapshots
82ba55b8f994ab30ff561a347b82ea340ba7075c
NOT_APPLICABLE
NOT_APPLICABLE
EvalSelectUnit(XtermWidget xw, Time buttonDownTime, SelectUnit defaultUnit, unsigned int button) { TScreen *screen = TScreenOf(xw); SelectUnit result; int delta; if (button != screen->lastButton) { delta = screen->multiClickTime + 1; } else if (screen->lastButtonUpTime == (Time) 0) { /* first time and once in a blue moon */ delta = screen->multiClickTime + 1; } else if (buttonDownTime > screen->lastButtonUpTime) { /* most of the time */ delta = (int) (buttonDownTime - screen->lastButtonUpTime); } else { /* time has rolled over since lastButtonUpTime */ delta = (int) ((((Time) ~ 0) - screen->lastButtonUpTime) + buttonDownTime); } if (delta > screen->multiClickTime) { screen->numberOfClicks = 1; result = defaultUnit; } else { result = screen->selectMap[screen->numberOfClicks % screen->maxClicks]; screen->numberOfClicks += 1; } TRACE(("EvalSelectUnit(%d) = %d\n", screen->numberOfClicks, result)); return result; }
0
radare2
7ab66cca5bbdf6cb2d69339ef4f513d95e532dbf
NOT_APPLICABLE
NOT_APPLICABLE
RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) { RASN1Object *object; RCMS *container; if (!buffer || !length) { return NULL; } container = R_NEW0 (RCMS); if (!container) { return NULL; } object = r_asn1_create_object (buffer, length); if (!object || object->list.length != 2 || !object->list.objects || !object->list.objects[0] || !object->list.objects[1] || object->list.objects[1]->list.length != 1) { r_asn1_free_object (object); free (container); return NULL; } container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length); r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]); r_asn1_free_object (object); return container; }
0
linux-2.6
9926e4c74300c4b31dee007298c6475d33369df0
NOT_APPLICABLE
NOT_APPLICABLE
asmlinkage long sys_newuname(struct new_utsname __user * name) { int errno = 0; down_read(&uts_sem); if (copy_to_user(name, utsname(), sizeof *name)) errno = -EFAULT; up_read(&uts_sem); return errno; }
0
libtiff
438274f938e046d33cb0e1230b41da32ffe223e1
NOT_APPLICABLE
NOT_APPLICABLE
TIFFReadTile(TIFF* tif, void* buf, uint32 x, uint32 y, uint32 z, uint16 s) { if (!TIFFCheckRead(tif, 1) || !TIFFCheckTile(tif, x, y, z, s)) return ((tmsize_t)(-1)); return (TIFFReadEncodedTile(tif, TIFFComputeTile(tif, x, y, z, s), buf, (tmsize_t)(-1))); }
0
ImageMagick
b5ed738f8060266bf4ae521f7e3ed145aa4498a3
NOT_APPLICABLE
NOT_APPLICABLE
MagickExport QuantumType GetQuantumType(Image *image,ExceptionInfo *exception) { QuantumType quantum_type; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); (void) exception; quantum_type=RGBQuantum; if (image->matte != MagickFalse) quantum_type=RGBAQuantum; if (image->colorspace == CMYKColorspace) { quantum_type=CMYKQuantum; if (image->matte != MagickFalse) quantum_type=CMYKAQuantum; } if (IsGrayColorspace(image->colorspace) != MagickFalse) { quantum_type=GrayQuantum; if (image->matte != MagickFalse) quantum_type=GrayAlphaQuantum; } if (image->storage_class == PseudoClass) { quantum_type=IndexQuantum; if (image->matte != MagickFalse) quantum_type=IndexAlphaQuantum; } return(quantum_type); }
0
FFmpeg
7ac5067146613997bb38442cb022d7f41321a706
NOT_APPLICABLE
NOT_APPLICABLE
static int decompress_p(AVCodecContext *avctx, uint32_t *dst, int linesize, uint32_t *prev, int plinesize) { SCPRContext *s = avctx->priv_data; GetByteContext *gb = &s->gb; int ret, temp, min, max, x, y, cx = 0, cx1 = 0; int backstep = linesize - avctx->width; const int cxshift = s->cxshift; if (bytestream2_get_byte(gb) == 0) return 0; bytestream2_skip(gb, 1); init_rangecoder(&s->rc, gb); ret = decode_value(s, s->range_model, 256, 1, &min); ret |= decode_value(s, s->range_model, 256, 1, &temp); min += temp << 8; ret |= decode_value(s, s->range_model, 256, 1, &max); ret |= decode_value(s, s->range_model, 256, 1, &temp); if (ret < 0) return ret; max += temp << 8; memset(s->blocks, 0, sizeof(*s->blocks) * s->nbcount); while (min <= max) { int fill, count; ret = decode_value(s, s->fill_model, 5, 10, &fill); ret |= decode_value(s, s->count_model, 256, 20, &count); if (ret < 0) return ret; while (min < s->nbcount && count-- > 0) { s->blocks[min++] = fill; } } for (y = 0; y < s->nby; y++) { for (x = 0; x < s->nbx; x++) { int sy1 = 0, sy2 = 16, sx1 = 0, sx2 = 16; if (s->blocks[y * s->nbx + x] == 0) continue; if (((s->blocks[y * s->nbx + x] - 1) & 1) > 0) { ret = decode_value(s, s->sxy_model[0], 16, 100, &sx1); ret |= decode_value(s, s->sxy_model[1], 16, 100, &sy1); ret |= decode_value(s, s->sxy_model[2], 16, 100, &sx2); ret |= decode_value(s, s->sxy_model[3], 16, 100, &sy2); if (ret < 0) return ret; sx2++; sy2++; } if (((s->blocks[y * s->nbx + x] - 1) & 2) > 0) { int i, j, by = y * 16, bx = x * 16; int mvx, mvy; ret = decode_value(s, s->mv_model[0], 512, 100, &mvx); ret |= decode_value(s, s->mv_model[1], 512, 100, &mvy); if (ret < 0) return ret; mvx -= 256; mvy -= 256; if (by + mvy + sy1 < 0 || bx + mvx + sx1 < 0 || by + mvy + sy1 >= avctx->height || bx + mvx + sx1 >= avctx->width) return AVERROR_INVALIDDATA; for (i = 0; i < sy2 - sy1 && (by + sy1 + i) < avctx->height && (by + mvy + sy1 + i) < avctx->height; i++) { for (j = 0; j < sx2 - sx1 && (bx + sx1 + j) < avctx->width && (bx + mvx + sx1 + j) < avctx->width; j++) { dst[(by + i + sy1) * linesize + bx + sx1 + j] = prev[(by + mvy + sy1 + i) * plinesize + bx + sx1 + mvx + j]; } } } else { int run, r, g, b, z, bx = x * 16 + sx1, by = y * 16 + sy1; unsigned clr, ptype = 0; for (; by < y * 16 + sy2 && by < avctx->height;) { ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype); if (ptype == 0) { ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = r >> cxshift; ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g); if (ret < 0) return ret; cx1 = (cx << 6) & 0xFC0; cx = g >> cxshift; ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b); if (ret < 0) return ret; clr = (b << 16) + (g << 8) + r; } if (ptype > 5) return AVERROR_INVALIDDATA; ret = decode_value(s, s->run_model[ptype], 256, 400, &run); if (ret < 0) return ret; switch (ptype) { case 0: while (run-- > 0) { if (by >= avctx->height) return AVERROR_INVALIDDATA; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 1: while (run-- > 0) { if (bx == 0) { if (by < 1) return AVERROR_INVALIDDATA; z = backstep; } else { z = 0; } if (by >= avctx->height) return AVERROR_INVALIDDATA; clr = dst[by * linesize + bx - 1 - z]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 2: while (run-- > 0) { if (by < 1 || by >= avctx->height) return AVERROR_INVALIDDATA; clr = dst[(by - 1) * linesize + bx]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 3: while (run-- > 0) { if (by >= avctx->height) return AVERROR_INVALIDDATA; clr = prev[by * plinesize + bx]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 4: while (run-- > 0) { uint8_t *odst = (uint8_t *)dst; if (by < 1 || by >= avctx->height) return AVERROR_INVALIDDATA; if (bx == 0) { z = backstep; } else { z = 0; } r = odst[((by - 1) * linesize + bx) * 4] + odst[(by * linesize + bx - 1 - z) * 4] - odst[((by - 1) * linesize + bx - 1 - z) * 4]; g = odst[((by - 1) * linesize + bx) * 4 + 1] + odst[(by * linesize + bx - 1 - z) * 4 + 1] - odst[((by - 1) * linesize + bx - 1 - z) * 4 + 1]; b = odst[((by - 1) * linesize + bx) * 4 + 2] + odst[(by * linesize + bx - 1 - z) * 4 + 2] - odst[((by - 1) * linesize + bx - 1 - z) * 4 + 2]; clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF); dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; case 5: while (run-- > 0) { if (by < 1 || by >= avctx->height) return AVERROR_INVALIDDATA; if (bx == 0) { z = backstep; } else { z = 0; } clr = dst[(by - 1) * linesize + bx - 1 - z]; dst[by * linesize + bx] = clr; bx++; if (bx >= x * 16 + sx2 || bx >= avctx->width) { bx = x * 16 + sx1; by++; } } break; } if (avctx->bits_per_coded_sample == 16) { cx1 = (clr & 0x3F00) >> 2; cx = (clr & 0xFFFFFF) >> 16; } else { cx1 = (clr & 0xFC00) >> 4; cx = (clr & 0xFFFFFF) >> 18; } } } } } return 0; }
0
libarchive
59357157706d47c365b2227739e17daba3607526
NOT_APPLICABLE
NOT_APPLICABLE
hfs_write_decmpfs_block(struct archive_write_disk *a, const char *buff, size_t size) { const char *buffer_to_write; size_t bytes_to_write; int ret; if (a->decmpfs_block_count == (unsigned)-1) { void *new_block; size_t new_size; unsigned int block_count; if (a->decmpfs_header_p == NULL) { new_block = malloc(MAX_DECMPFS_XATTR_SIZE + sizeof(uint32_t)); if (new_block == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for decmpfs"); return (ARCHIVE_FATAL); } a->decmpfs_header_p = new_block; } a->decmpfs_attr_size = DECMPFS_HEADER_SIZE; archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_MAGIC], DECMPFS_MAGIC); archive_le32enc(&a->decmpfs_header_p[DECMPFS_COMPRESSION_TYPE], CMP_RESOURCE_FORK); archive_le64enc(&a->decmpfs_header_p[DECMPFS_UNCOMPRESSED_SIZE], a->filesize); /* Calculate a block count of the file. */ block_count = (a->filesize + MAX_DECMPFS_BLOCK_SIZE -1) / MAX_DECMPFS_BLOCK_SIZE; /* * Allocate buffer for resource fork. * Set up related pointers; */ new_size = RSRC_H_SIZE + /* header */ 4 + /* Block count */ (block_count * sizeof(uint32_t) * 2) + RSRC_F_SIZE; /* footer */ if (new_size > a->resource_fork_allocated_size) { new_block = realloc(a->resource_fork, new_size); if (new_block == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for ResourceFork"); return (ARCHIVE_FATAL); } a->resource_fork_allocated_size = new_size; a->resource_fork = new_block; } /* Allocate uncompressed buffer */ if (a->uncompressed_buffer == NULL) { new_block = malloc(MAX_DECMPFS_BLOCK_SIZE); if (new_block == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for decmpfs"); return (ARCHIVE_FATAL); } a->uncompressed_buffer = new_block; } a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE; a->file_remaining_bytes = a->filesize; a->compressed_buffer_remaining = a->compressed_buffer_size; /* * Set up a resource fork. */ a->rsrc_xattr_options = XATTR_CREATE; /* Get the position where we are going to set a bunch * of block info. */ a->decmpfs_block_info = (uint32_t *)(a->resource_fork + RSRC_H_SIZE); /* Set the block count to the resource fork. */ archive_le32enc(a->decmpfs_block_info++, block_count); /* Get the position where we are goint to set compressed * data. */ a->compressed_rsrc_position = RSRC_H_SIZE + 4 + (block_count * 8); a->compressed_rsrc_position_v = a->compressed_rsrc_position; a->decmpfs_block_count = block_count; } /* Ignore redundant bytes. */ if (a->file_remaining_bytes == 0) return ((ssize_t)size); /* Do not overrun a block size. */ if (size > a->block_remaining_bytes) bytes_to_write = a->block_remaining_bytes; else bytes_to_write = size; /* Do not overrun the file size. */ if (bytes_to_write > a->file_remaining_bytes) bytes_to_write = a->file_remaining_bytes; /* For efficiency, if a copy length is full of the uncompressed * buffer size, do not copy writing data to it. */ if (bytes_to_write == MAX_DECMPFS_BLOCK_SIZE) buffer_to_write = buff; else { memcpy(a->uncompressed_buffer + MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes, buff, bytes_to_write); buffer_to_write = a->uncompressed_buffer; } a->block_remaining_bytes -= bytes_to_write; a->file_remaining_bytes -= bytes_to_write; if (a->block_remaining_bytes == 0 || a->file_remaining_bytes == 0) { ret = hfs_drive_compressor(a, buffer_to_write, MAX_DECMPFS_BLOCK_SIZE - a->block_remaining_bytes); if (ret < 0) return (ret); a->block_remaining_bytes = MAX_DECMPFS_BLOCK_SIZE; } /* Ignore redundant bytes. */ if (a->file_remaining_bytes == 0) return ((ssize_t)size); return (bytes_to_write); }
0
ImageMagick6
35c7032723d85eee7318ff6c82f031fa2666b773
NOT_APPLICABLE
NOT_APPLICABLE
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); }
0
linux
c1fa0768a8713b135848f78fd43ffc208d8ded70
NOT_APPLICABLE
NOT_APPLICABLE
static int tm_cvmx_get(struct task_struct *target, const struct user_regset *regset, unsigned int pos, unsigned int count, void *kbuf, void __user *ubuf) { int ret; BUILD_BUG_ON(TVSO(vscr) != TVSO(vr[32])); if (!cpu_has_feature(CPU_FTR_TM)) return -ENODEV; if (!MSR_TM_ACTIVE(target->thread.regs->msr)) return -ENODATA; /* Flush the state */ flush_tmregs_to_thread(target); flush_fp_to_thread(target); flush_altivec_to_thread(target); ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, &target->thread.ckvr_state, 0, 33 * sizeof(vector128)); if (!ret) { /* * Copy out only the low-order word of vrsave. */ union { elf_vrreg_t reg; u32 word; } vrsave; memset(&vrsave, 0, sizeof(vrsave)); vrsave.word = target->thread.ckvrsave; ret = user_regset_copyout(&pos, &count, &kbuf, &ubuf, &vrsave, 33 * sizeof(vector128), -1); } return ret; }
0
linux
d7a6be58edc01b1c66ecd8fcc91236bfbce0a420
NOT_APPLICABLE
NOT_APPLICABLE
static int available_error_type_show(struct seq_file *m, void *v) { int rc; u32 available_error_type = 0; rc = einj_get_available_error_type(&available_error_type); if (rc) return rc; if (available_error_type & 0x0001) seq_printf(m, "0x00000001\tProcessor Correctable\n"); if (available_error_type & 0x0002) seq_printf(m, "0x00000002\tProcessor Uncorrectable non-fatal\n"); if (available_error_type & 0x0004) seq_printf(m, "0x00000004\tProcessor Uncorrectable fatal\n"); if (available_error_type & 0x0008) seq_printf(m, "0x00000008\tMemory Correctable\n"); if (available_error_type & 0x0010) seq_printf(m, "0x00000010\tMemory Uncorrectable non-fatal\n"); if (available_error_type & 0x0020) seq_printf(m, "0x00000020\tMemory Uncorrectable fatal\n"); if (available_error_type & 0x0040) seq_printf(m, "0x00000040\tPCI Express Correctable\n"); if (available_error_type & 0x0080) seq_printf(m, "0x00000080\tPCI Express Uncorrectable non-fatal\n"); if (available_error_type & 0x0100) seq_printf(m, "0x00000100\tPCI Express Uncorrectable fatal\n"); if (available_error_type & 0x0200) seq_printf(m, "0x00000200\tPlatform Correctable\n"); if (available_error_type & 0x0400) seq_printf(m, "0x00000400\tPlatform Uncorrectable non-fatal\n"); if (available_error_type & 0x0800) seq_printf(m, "0x00000800\tPlatform Uncorrectable fatal\n"); return 0; }
0
weechat
40ccacb4330a64802b1f1e28ed9a6b6d3ca9197f
NOT_APPLICABLE
NOT_APPLICABLE
irc_nick_get_color_for_nicklist (struct t_irc_server *server, struct t_irc_nick *nick) { static char *nick_color_bar_fg = "bar_fg"; static char *nick_color_self = "weechat.color.chat_nick_self"; static char *nick_color_away = "weechat.color.nicklist_away"; if (nick->away) return strdup (nick_color_away); if (weechat_config_boolean (irc_config_look_color_nicks_in_nicklist)) { if (irc_server_strcasecmp (server, nick->name, server->nick) == 0) return strdup (nick_color_self); else return irc_nick_find_color_name (nick->name); } return strdup (nick_color_bar_fg); }
0
linux
606142af57dad981b78707234cfbd15f9f7b7125
CVE-2017-8062
CWE-119
static int tt_s2_4600_frontend_attach(struct dvb_usb_adapter *adap) { struct dvb_usb_device *d = adap->dev; struct dw2102_state *state = d->priv; u8 obuf[3] = { 0xe, 0x80, 0 }; u8 ibuf[] = { 0 }; struct i2c_adapter *i2c_adapter; struct i2c_client *client; struct i2c_board_info board_info; struct m88ds3103_platform_data m88ds3103_pdata = {}; struct ts2020_config ts2020_config = {}; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x02; obuf[2] = 1; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); msleep(300); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 0; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0xe; obuf[1] = 0x83; obuf[2] = 1; if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) err("command 0x0e transfer failed."); obuf[0] = 0x51; if (dvb_usb_generic_rw(d, obuf, 1, ibuf, 1, 0) < 0) err("command 0x51 transfer failed."); /* attach demod */ m88ds3103_pdata.clk = 27000000; m88ds3103_pdata.i2c_wr_max = 33; m88ds3103_pdata.ts_mode = M88DS3103_TS_CI; m88ds3103_pdata.ts_clk = 16000; m88ds3103_pdata.ts_clk_pol = 0; m88ds3103_pdata.spec_inv = 0; m88ds3103_pdata.agc = 0x99; m88ds3103_pdata.agc_inv = 0; m88ds3103_pdata.clk_out = M88DS3103_CLOCK_OUT_ENABLED; m88ds3103_pdata.envelope_mode = 0; m88ds3103_pdata.lnb_hv_pol = 1; m88ds3103_pdata.lnb_en_pol = 0; memset(&board_info, 0, sizeof(board_info)); strlcpy(board_info.type, "m88ds3103", I2C_NAME_SIZE); board_info.addr = 0x68; board_info.platform_data = &m88ds3103_pdata; request_module("m88ds3103"); client = i2c_new_device(&d->i2c_adap, &board_info); if (client == NULL || client->dev.driver == NULL) return -ENODEV; if (!try_module_get(client->dev.driver->owner)) { i2c_unregister_device(client); return -ENODEV; } adap->fe_adap[0].fe = m88ds3103_pdata.get_dvb_frontend(client); i2c_adapter = m88ds3103_pdata.get_i2c_adapter(client); state->i2c_client_demod = client; /* attach tuner */ ts2020_config.fe = adap->fe_adap[0].fe; memset(&board_info, 0, sizeof(board_info)); strlcpy(board_info.type, "ts2022", I2C_NAME_SIZE); board_info.addr = 0x60; board_info.platform_data = &ts2020_config; request_module("ts2020"); client = i2c_new_device(i2c_adapter, &board_info); if (client == NULL || client->dev.driver == NULL) { dvb_frontend_detach(adap->fe_adap[0].fe); return -ENODEV; } if (!try_module_get(client->dev.driver->owner)) { i2c_unregister_device(client); dvb_frontend_detach(adap->fe_adap[0].fe); return -ENODEV; } /* delegate signal strength measurement to tuner */ adap->fe_adap[0].fe->ops.read_signal_strength = adap->fe_adap[0].fe->ops.tuner_ops.get_rf_strength; state->i2c_client_tuner = client; /* hook fe: need to resync the slave fifo when signal locks */ state->fe_read_status = adap->fe_adap[0].fe->ops.read_status; adap->fe_adap[0].fe->ops.read_status = tt_s2_4600_read_status; state->last_lock = 0; return 0; }
1
FFmpeg
c24bcb553650b91e9eff15ef6e54ca73de2453b7
NOT_APPLICABLE
NOT_APPLICABLE
static int nsv_parse_NSVs_header(AVFormatContext *s) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; uint32_t vtag, atag; uint16_t vwidth, vheight; AVRational framerate; int i; AVStream *st; NSVStream *nst; vtag = avio_rl32(pb); atag = avio_rl32(pb); vwidth = avio_rl16(pb); vheight = avio_rl16(pb); i = avio_r8(pb); av_log(s, AV_LOG_TRACE, "NSV NSVs framerate code %2x\n", i); if(i&0x80) { /* odd way of giving native framerates from docs */ int t=(i & 0x7F)>>2; if(t<16) framerate = (AVRational){1, t+1}; else framerate = (AVRational){t-15, 1}; if(i&1){ framerate.num *= 1000; framerate.den *= 1001; } if((i&3)==3) framerate.num *= 24; else if((i&3)==2) framerate.num *= 25; else framerate.num *= 30; } else framerate= (AVRational){i, 1}; nsv->avsync = avio_rl16(pb); nsv->framerate = framerate; av_log(s, AV_LOG_TRACE, "NSV NSVs vsize %dx%d\n", vwidth, vheight); /* XXX change to ap != NULL ? */ if (s->nb_streams == 0) { /* streams not yet published, let's do that */ nsv->vtag = vtag; nsv->atag = atag; nsv->vwidth = vwidth; nsv->vheight = vwidth; if (vtag != T_NONE) { int i; st = avformat_new_stream(s, NULL); if (!st) goto fail; st->id = NSV_ST_VIDEO; nst = av_mallocz(sizeof(NSVStream)); if (!nst) goto fail; st->priv_data = nst; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_tag = vtag; st->codecpar->codec_id = ff_codec_get_id(nsv_codec_video_tags, vtag); st->codecpar->width = vwidth; st->codecpar->height = vheight; st->codecpar->bits_per_coded_sample = 24; /* depth XXX */ avpriv_set_pts_info(st, 64, framerate.den, framerate.num); st->start_time = 0; st->duration = av_rescale(nsv->duration, framerate.num, 1000*framerate.den); for(i=0;i<nsv->index_entries;i++) { if(nsv->nsvs_timestamps) { av_add_index_entry(st, nsv->nsvs_file_offset[i], nsv->nsvs_timestamps[i], 0, 0, AVINDEX_KEYFRAME); } else { int64_t ts = av_rescale(i*nsv->duration/nsv->index_entries, framerate.num, 1000*framerate.den); av_add_index_entry(st, nsv->nsvs_file_offset[i], ts, 0, 0, AVINDEX_KEYFRAME); } } } if (atag != T_NONE) { st = avformat_new_stream(s, NULL); if (!st) goto fail; st->id = NSV_ST_AUDIO; nst = av_mallocz(sizeof(NSVStream)); if (!nst) goto fail; st->priv_data = nst; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_tag = atag; st->codecpar->codec_id = ff_codec_get_id(nsv_codec_audio_tags, atag); st->need_parsing = AVSTREAM_PARSE_FULL; /* for PCM we will read a chunk later and put correct info */ /* set timebase to common denominator of ms and framerate */ avpriv_set_pts_info(st, 64, 1, framerate.num*1000); st->start_time = 0; st->duration = (int64_t)nsv->duration * framerate.num; } } else { if (nsv->vtag != vtag || nsv->atag != atag || nsv->vwidth != vwidth || nsv->vheight != vwidth) { av_log(s, AV_LOG_TRACE, "NSV NSVs header values differ from the first one!!!\n"); } } nsv->state = NSV_HAS_READ_NSVS; return 0; fail: /* XXX */ nsv->state = NSV_UNSYNC; return -1; }
0
linux
13e4ad2ce8df6e058ef482a31fdd81c725b0f7ea
NOT_APPLICABLE
NOT_APPLICABLE
static vm_fault_t hugetlb_no_page(struct mm_struct *mm, struct vm_area_struct *vma, struct address_space *mapping, pgoff_t idx, unsigned long address, pte_t *ptep, unsigned int flags) { struct hstate *h = hstate_vma(vma); vm_fault_t ret = VM_FAULT_SIGBUS; int anon_rmap = 0; unsigned long size; struct page *page; pte_t new_pte; spinlock_t *ptl; unsigned long haddr = address & huge_page_mask(h); bool new_page, new_pagecache_page = false; /* * Currently, we are forced to kill the process in the event the * original mapper has unmapped pages from the child due to a failed * COW. Warn that such a situation has occurred as it may not be obvious */ if (is_vma_resv_set(vma, HPAGE_RESV_UNMAPPED)) { pr_warn_ratelimited("PID %d killed due to inadequate hugepage pool\n", current->pid); return ret; } /* * We can not race with truncation due to holding i_mmap_rwsem. * i_size is modified when holding i_mmap_rwsem, so check here * once for faults beyond end of file. */ size = i_size_read(mapping->host) >> huge_page_shift(h); if (idx >= size) goto out; retry: new_page = false; page = find_lock_page(mapping, idx); if (!page) { /* Check for page in userfault range */ if (userfaultfd_missing(vma)) { ret = hugetlb_handle_userfault(vma, mapping, idx, flags, haddr, VM_UFFD_MISSING); goto out; } page = alloc_huge_page(vma, haddr, 0); if (IS_ERR(page)) { /* * Returning error will result in faulting task being * sent SIGBUS. The hugetlb fault mutex prevents two * tasks from racing to fault in the same page which * could result in false unable to allocate errors. * Page migration does not take the fault mutex, but * does a clear then write of pte's under page table * lock. Page fault code could race with migration, * notice the clear pte and try to allocate a page * here. Before returning error, get ptl and make * sure there really is no pte entry. */ ptl = huge_pte_lock(h, mm, ptep); ret = 0; if (huge_pte_none(huge_ptep_get(ptep))) ret = vmf_error(PTR_ERR(page)); spin_unlock(ptl); goto out; } clear_huge_page(page, address, pages_per_huge_page(h)); __SetPageUptodate(page); new_page = true; if (vma->vm_flags & VM_MAYSHARE) { int err = huge_add_to_page_cache(page, mapping, idx); if (err) { put_page(page); if (err == -EEXIST) goto retry; goto out; } new_pagecache_page = true; } else { lock_page(page); if (unlikely(anon_vma_prepare(vma))) { ret = VM_FAULT_OOM; goto backout_unlocked; } anon_rmap = 1; } } else { /* * If memory error occurs between mmap() and fault, some process * don't have hwpoisoned swap entry for errored virtual address. * So we need to block hugepage fault by PG_hwpoison bit check. */ if (unlikely(PageHWPoison(page))) { ret = VM_FAULT_HWPOISON_LARGE | VM_FAULT_SET_HINDEX(hstate_index(h)); goto backout_unlocked; } /* Check for page in userfault range. */ if (userfaultfd_minor(vma)) { unlock_page(page); put_page(page); ret = hugetlb_handle_userfault(vma, mapping, idx, flags, haddr, VM_UFFD_MINOR); goto out; } } /* * If we are going to COW a private mapping later, we examine the * pending reservations for this page now. This will ensure that * any allocations necessary to record that reservation occur outside * the spinlock. */ if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) { if (vma_needs_reservation(h, vma, haddr) < 0) { ret = VM_FAULT_OOM; goto backout_unlocked; } /* Just decrements count, does not deallocate */ vma_end_reservation(h, vma, haddr); } ptl = huge_pte_lock(h, mm, ptep); ret = 0; if (!huge_pte_none(huge_ptep_get(ptep))) goto backout; if (anon_rmap) { ClearHPageRestoreReserve(page); hugepage_add_new_anon_rmap(page, vma, haddr); } else page_dup_rmap(page, true); new_pte = make_huge_pte(vma, page, ((vma->vm_flags & VM_WRITE) && (vma->vm_flags & VM_SHARED))); set_huge_pte_at(mm, haddr, ptep, new_pte); hugetlb_count_add(pages_per_huge_page(h), mm); if ((flags & FAULT_FLAG_WRITE) && !(vma->vm_flags & VM_SHARED)) { /* Optimization, do the COW without a second fault */ ret = hugetlb_cow(mm, vma, address, ptep, page, ptl); } spin_unlock(ptl); /* * Only set HPageMigratable in newly allocated pages. Existing pages * found in the pagecache may not have HPageMigratableset if they have * been isolated for migration. */ if (new_page) SetHPageMigratable(page); unlock_page(page); out: return ret; backout: spin_unlock(ptl); backout_unlocked: unlock_page(page); /* restore reserve for newly allocated pages not in page cache */ if (new_page && !new_pagecache_page) restore_reserve_on_error(h, vma, haddr, page); put_page(page); goto out; }
0
bluez
8cdbd3b09f29da29374e2f83369df24228da0ad1
NOT_APPLICABLE
NOT_APPLICABLE
static struct hog_device *hog_device_new(struct btd_device *device) { struct hog_device *dev; dev = new0(struct hog_device, 1); dev->device = btd_device_ref(device); if (!devices) devices = queue_new(); queue_push_tail(devices, dev); return dev; }
0
ImageMagick
ef59bd764f88d893f1219fee8ba696a5d3f8c1c4
NOT_APPLICABLE
NOT_APPLICABLE
MagickExport Image *CompareImagesLayers(const Image *image, const LayerMethod method,ExceptionInfo *exception) { Image *image_a, *image_b, *layers; RectangleInfo *bounds; register const Image *next; register ssize_t i; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert((method == CompareAnyLayer) || (method == CompareClearLayer) || (method == CompareOverlayLayer)); /* Allocate bounds memory. */ next=GetFirstImageInList(image); bounds=(RectangleInfo *) AcquireQuantumMemory((size_t) GetImageListLength(next),sizeof(*bounds)); if (bounds == (RectangleInfo *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Set up first comparision images. */ image_a=CloneImage(next,next->page.width,next->page.height, MagickTrue,exception); if (image_a == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_a->background_color.alpha_trait=BlendPixelTrait; image_a->background_color.alpha=(MagickRealType) TransparentAlpha; (void) SetImageBackgroundColor(image_a,exception); image_a->page=next->page; image_a->page.x=0; image_a->page.y=0; (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); /* Compute the bounding box of changes for the later images */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { image_b=CloneImage(image_a,0,0,MagickTrue,exception); if (image_b == (Image *) NULL) { image_a=DestroyImage(image_a); bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } image_b->background_color.alpha_trait=BlendPixelTrait; (void) CompositeImage(image_a,next,CopyCompositeOp,MagickTrue,next->page.x, next->page.y,exception); bounds[i]=CompareImagesBounds(image_b,image_a,method,exception); image_b=DestroyImage(image_b); i++; } image_a=DestroyImage(image_a); /* Clone first image in sequence. */ next=GetFirstImageInList(image); layers=CloneImage(next,0,0,MagickTrue,exception); if (layers == (Image *) NULL) { bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); return((Image *) NULL); } layers->background_color.alpha_trait=BlendPixelTrait; /* Deconstruct the image sequence. */ i=0; next=GetNextImageInList(next); for ( ; next != (const Image *) NULL; next=GetNextImageInList(next)) { if ((bounds[i].x == -1) && (bounds[i].y == -1) && (bounds[i].width == 1) && (bounds[i].height == 1)) { /* An empty frame is returned from CompareImageBounds(), which means the current frame is identical to the previous frame. */ i++; continue; } image_a=CloneImage(next,0,0,MagickTrue,exception); if (image_a == (Image *) NULL) break; image_a->background_color.alpha_trait=BlendPixelTrait; image_b=CropImage(image_a,&bounds[i],exception); image_a=DestroyImage(image_a); if (image_b == (Image *) NULL) break; AppendImageToList(&layers,image_b); i++; } bounds=(RectangleInfo *) RelinquishMagickMemory(bounds); if (next != (Image *) NULL) { layers=DestroyImageList(layers); return((Image *) NULL); } return(GetFirstImageInList(layers)); }
0
FFmpeg
900f39692ca0337a98a7cf047e4e2611071810c2
NOT_APPLICABLE
NOT_APPLICABLE
static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset) { MXFContext *mxf = arg; AVFormatContext *s = mxf->fc; int ret; UID uid = { 0 }; char *str = NULL; uint64_t ts; switch (tag) { case 0x3C01: SET_STR_METADATA(pb, "company_name", str); break; case 0x3C02: SET_STR_METADATA(pb, "product_name", str); break; case 0x3C04: SET_STR_METADATA(pb, "product_version", str); break; case 0x3C05: SET_UID_METADATA(pb, "product_uid", uid, str); break; case 0x3C06: SET_TS_METADATA(pb, "modification_date", ts, str); break; case 0x3C08: SET_STR_METADATA(pb, "application_platform", str); break; case 0x3C09: SET_UID_METADATA(pb, "generation_uid", uid, str); break; case 0x3C0A: SET_UID_METADATA(pb, "uid", uid, str); break; } return 0; }
0
linux
3446c13b268af86391d06611327006b059b8bab1
NOT_APPLICABLE
NOT_APPLICABLE
static inline void clear_user_asce(void) { S390_lowcore.user_asce = S390_lowcore.kernel_asce; __ctl_load(S390_lowcore.user_asce, 1, 1); __ctl_load(S390_lowcore.user_asce, 7, 7); }
0
NetworkManager
d5fc88e573fa58b93034b04d35a2454f5d28cad9
CVE-2015-0272
CWE-20
device_has_capability (NMDevice *self, NMDeviceCapabilities caps) { { static guint32 devcount = 0; NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->path == NULL); priv->path = g_strdup_printf ("/org/freedesktop/NetworkManager/Devices/%d", devcount++); _LOGI (LOGD_DEVICE, "exported as %s", priv->path); nm_dbus_manager_register_object (nm_dbus_manager_get (), priv->path, self); } const char * nm_device_get_path (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->path; } const char * nm_device_get_udi (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->udi; } const char * nm_device_get_iface (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), 0); return NM_DEVICE_GET_PRIVATE (self)->iface; } int nm_device_get_ifindex (NMDevice *self) { g_return_val_if_fail (self != NULL, 0); return NM_DEVICE_GET_PRIVATE (self)->ifindex; } gboolean nm_device_is_software (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); return priv->is_software; } const char * nm_device_get_ip_iface (NMDevice *self) { NMDevicePrivate *priv; g_return_val_if_fail (self != NULL, NULL); priv = NM_DEVICE_GET_PRIVATE (self); /* If it's not set, default to iface */ return priv->ip_iface ? priv->ip_iface : priv->iface; } int nm_device_get_ip_ifindex (NMDevice *self) { NMDevicePrivate *priv; g_return_val_if_fail (self != NULL, 0); priv = NM_DEVICE_GET_PRIVATE (self); /* If it's not set, default to iface */ return priv->ip_iface ? priv->ip_ifindex : priv->ifindex; } void nm_device_set_ip_iface (NMDevice *self, const char *iface) { NMDevicePrivate *priv; char *old_ip_iface; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); if (!g_strcmp0 (iface, priv->ip_iface)) return; old_ip_iface = priv->ip_iface; priv->ip_ifindex = 0; priv->ip_iface = g_strdup (iface); if (priv->ip_iface) { priv->ip_ifindex = nm_platform_link_get_ifindex (priv->ip_iface); if (priv->ip_ifindex > 0) { if (nm_platform_check_support_user_ipv6ll ()) nm_platform_link_set_user_ipv6ll_enabled (priv->ip_ifindex, TRUE); if (!nm_platform_link_is_up (priv->ip_ifindex)) nm_platform_link_set_up (priv->ip_ifindex); } else { /* Device IP interface must always be a kernel network interface */ _LOGW (LOGD_HW, "failed to look up interface index"); } } /* We don't care about any saved values from the old iface */ g_hash_table_remove_all (priv->ip6_saved_properties); /* Emit change notification */ if (g_strcmp0 (old_ip_iface, priv->ip_iface)) g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); g_free (old_ip_iface); } static gboolean get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *out_iid) { NMLinkType link_type; const guint8 *hwaddr = NULL; size_t hwaddr_len = 0; int ifindex; gboolean success; /* If we get here, we *must* have a kernel netdev, which implies an ifindex */ ifindex = nm_device_get_ip_ifindex (self); g_assert (ifindex); link_type = nm_platform_link_get_type (ifindex); g_return_val_if_fail (link_type > NM_LINK_TYPE_UNKNOWN, 0); hwaddr = nm_platform_link_get_address (ifindex, &hwaddr_len); if (!hwaddr_len) return FALSE; success = nm_utils_get_ipv6_interface_identifier (link_type, hwaddr, hwaddr_len, out_iid); if (!success) { _LOGW (LOGD_HW, "failed to generate interface identifier " "for link type %u hwaddr_len %zu", link_type, hwaddr_len); } return success; } static gboolean nm_device_get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *iid) { return NM_DEVICE_GET_CLASS (self)->get_ip_iface_identifier (self, iid); } const char * nm_device_get_driver (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->driver; } const char * nm_device_get_driver_version (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->driver_version; } NMDeviceType nm_device_get_device_type (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_TYPE_UNKNOWN); return NM_DEVICE_GET_PRIVATE (self)->type; } /** * nm_device_get_priority(): * @self: the #NMDevice * * Returns: the device's routing priority. Lower numbers means a "better" * device, eg higher priority. */ int nm_device_get_priority (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), 1000); /* Device 'priority' is used for the default route-metric and is based on * the device type. The settings ipv4.route-metric and ipv6.route-metric * can overwrite this default. * * Currently for both IPv4 and IPv6 we use the same default values. * * The route-metric is used for the metric of the routes of device. * This also applies to the default route. Therefore it affects also * which device is the "best". * * For comparison, note that iproute2 by default adds IPv4 routes with * metric 0, and IPv6 routes with metric 1024. The latter is the IPv6 * "user default" in the kernel (NM_PLATFORM_ROUTE_METRIC_DEFAULT_IP6). * In kernel, the full uint32_t range is available for route * metrics (except for IPv6, where 0 means 1024). */ switch (nm_device_get_device_type (self)) { /* 50 is reserved for VPN (NM_VPN_ROUTE_METRIC_DEFAULT) */ case NM_DEVICE_TYPE_ETHERNET: return 100; case NM_DEVICE_TYPE_INFINIBAND: return 150; case NM_DEVICE_TYPE_ADSL: return 200; case NM_DEVICE_TYPE_WIMAX: return 250; case NM_DEVICE_TYPE_BOND: return 300; case NM_DEVICE_TYPE_TEAM: return 350; case NM_DEVICE_TYPE_VLAN: return 400; case NM_DEVICE_TYPE_BRIDGE: return 425; case NM_DEVICE_TYPE_MODEM: return 450; case NM_DEVICE_TYPE_BT: return 550; case NM_DEVICE_TYPE_WIFI: return 600; case NM_DEVICE_TYPE_OLPC_MESH: return 650; case NM_DEVICE_TYPE_GENERIC: return 950; case NM_DEVICE_TYPE_UNKNOWN: return 10000; case NM_DEVICE_TYPE_UNUSED1: case NM_DEVICE_TYPE_UNUSED2: /* omit default: to get compiler warning about missing switch cases */ break; } return 11000; } guint32 nm_device_get_ip4_route_metric (NMDevice *self) { NMConnection *connection; gint64 route_metric = -1; g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32); connection = nm_device_get_connection (self); if (connection) route_metric = nm_setting_ip_config_get_route_metric (nm_connection_get_setting_ip4_config (connection)); return route_metric >= 0 ? route_metric : nm_device_get_priority (self); } guint32 nm_device_get_ip6_route_metric (NMDevice *self) { NMConnection *connection; gint64 route_metric = -1; g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32); connection = nm_device_get_connection (self); if (connection) route_metric = nm_setting_ip_config_get_route_metric (nm_connection_get_setting_ip6_config (connection)); return route_metric >= 0 ? route_metric : nm_device_get_priority (self); } const NMPlatformIP4Route * nm_device_get_ip4_default_route (NMDevice *self, gboolean *out_is_assumed) { NMDevicePrivate *priv; g_return_val_if_fail (NM_IS_DEVICE (self), NULL); priv = NM_DEVICE_GET_PRIVATE (self); if (out_is_assumed) *out_is_assumed = priv->default_route.v4_is_assumed; return priv->default_route.v4_has ? &priv->default_route.v4 : NULL; } const NMPlatformIP6Route * nm_device_get_ip6_default_route (NMDevice *self, gboolean *out_is_assumed) { NMDevicePrivate *priv; g_return_val_if_fail (NM_IS_DEVICE (self), NULL); priv = NM_DEVICE_GET_PRIVATE (self); if (out_is_assumed) *out_is_assumed = priv->default_route.v6_is_assumed; return priv->default_route.v6_has ? &priv->default_route.v6 : NULL; } const char * nm_device_get_type_desc (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->type_desc; } gboolean nm_device_has_carrier (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->carrier; } NMActRequest * nm_device_get_act_request (NMDevice *self) { g_return_val_if_fail (self != NULL, NULL); return NM_DEVICE_GET_PRIVATE (self)->act_request; } NMConnection * nm_device_get_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); return priv->act_request ? nm_act_request_get_connection (priv->act_request) : NULL; } RfKillType nm_device_get_rfkill_type (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); return NM_DEVICE_GET_PRIVATE (self)->rfkill_type; } static const char * nm_device_get_physical_port_id (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->physical_port_id; } /***********************************************************/ static gboolean nm_device_uses_generated_assumed_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; if ( priv->act_request && nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request))) { connection = nm_act_request_get_connection (priv->act_request); if ( connection && nm_settings_connection_get_nm_generated_assumed (NM_SETTINGS_CONNECTION (connection))) return TRUE; } return FALSE; } gboolean nm_device_uses_assumed_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if ( priv->act_request && nm_active_connection_get_assumed (NM_ACTIVE_CONNECTION (priv->act_request))) return TRUE; return FALSE; } static SlaveInfo * find_slave_info (NMDevice *self, NMDevice *slave) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; GSList *iter; for (iter = priv->slaves; iter; iter = g_slist_next (iter)) { info = iter->data; if (info->slave == slave) return info; } return NULL; } static void free_slave_info (SlaveInfo *info) { g_signal_handler_disconnect (info->slave, info->watch_id); g_clear_object (&info->slave); memset (info, 0, sizeof (*info)); g_free (info); } /** * nm_device_enslave_slave: * @self: the master device * @slave: the slave device to enslave * @connection: (allow-none): the slave device's connection * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function enslaves @slave. * * Returns: %TRUE on success, %FALSE on failure or if this device cannot enslave * other devices. */ static gboolean nm_device_enslave_slave (NMDevice *self, NMDevice *slave, NMConnection *connection) { SlaveInfo *info; gboolean success = FALSE; gboolean configure; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE); info = find_slave_info (self, slave); if (!info) return FALSE; if (info->enslaved) success = TRUE; else { configure = (info->configure && connection != NULL); if (configure) g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE); success = NM_DEVICE_GET_CLASS (self)->enslave_slave (self, slave, connection, configure); info->enslaved = success; } nm_device_slave_notify_enslave (info->slave, success); /* Ensure the device's hardware address is up-to-date; it often changes * when slaves change. */ nm_device_update_hw_address (self); /* Restart IP configuration if we're waiting for slaves. Do this * after updating the hardware address as IP config may need the * new address. */ if (success) { if (NM_DEVICE_GET_PRIVATE (self)->ip4_state == IP_WAIT) nm_device_activate_stage3_ip4_start (self); if (NM_DEVICE_GET_PRIVATE (self)->ip6_state == IP_WAIT) nm_device_activate_stage3_ip6_start (self); } return success; } /** * nm_device_release_one_slave: * @self: the master device * @slave: the slave device to release * @configure: whether @self needs to actually release @slave * @reason: the state change reason for the @slave * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function releases the previously enslaved @slave and/or * updates the state of @self and @slave to reflect its release. * * Returns: %TRUE on success, %FALSE on failure, if this device cannot enslave * other devices, or if @slave was never enslaved. */ static gboolean nm_device_release_one_slave (NMDevice *self, NMDevice *slave, gboolean configure, NMDeviceStateReason reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; gboolean success = FALSE; g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->release_slave != NULL, FALSE); info = find_slave_info (self, slave); if (!info) return FALSE; priv->slaves = g_slist_remove (priv->slaves, info); if (info->enslaved) { success = NM_DEVICE_GET_CLASS (self)->release_slave (self, slave, configure); /* The release_slave() implementation logs success/failure (in the * correct device-specific log domain), so we don't have to do anything. */ } if (!configure) { g_warn_if_fail (reason == NM_DEVICE_STATE_REASON_NONE || reason == NM_DEVICE_STATE_REASON_REMOVED); reason = NM_DEVICE_STATE_REASON_NONE; } else if (reason == NM_DEVICE_STATE_REASON_NONE) { g_warn_if_reached (); reason = NM_DEVICE_STATE_REASON_UNKNOWN; } nm_device_slave_notify_release (info->slave, reason); free_slave_info (info); /* Ensure the device's hardware address is up-to-date; it often changes * when slaves change. */ nm_device_update_hw_address (self); return success; } static gboolean is_software_external (NMDevice *self) { return nm_device_is_software (self) && !nm_device_get_is_nm_owned (self); } /** * nm_device_finish_init: * @self: the master device * * Whatever needs to be done post-initialization, when the device has a DBus * object name. */ void nm_device_finish_init (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_assert (priv->initialized == FALSE); /* Do not manage externally created software devices until they are IFF_UP */ if ( is_software_external (self) && !nm_platform_link_is_up (priv->ifindex) && priv->ifindex > 0) nm_device_set_initial_unmanaged_flag (self, NM_UNMANAGED_EXTERNAL_DOWN, TRUE); if (priv->master) nm_device_enslave_slave (priv->master, self, NULL); priv->initialized = TRUE; } static void carrier_changed (NMDevice *self, gboolean carrier) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (!nm_device_get_managed (self)) return; nm_device_recheck_available_connections (self); /* ignore-carrier devices ignore all carrier-down events */ if (priv->ignore_carrier && !carrier) return; if (priv->is_master) { /* Bridge/bond/team carrier does not affect its own activation, * but when carrier comes on, if there are slaves waiting, * it will restart them. */ if (!carrier) return; if (nm_device_activate_ip4_state_in_wait (self)) nm_device_activate_stage3_ip4_start (self); if (nm_device_activate_ip6_state_in_wait (self)) nm_device_activate_stage3_ip6_start (self); return; } else if (nm_device_get_enslaved (self) && !carrier) { /* Slaves don't deactivate when they lose carrier; for * bonds/teams in particular that would be actively * counterproductive. */ return; } if (carrier) { g_warn_if_fail (priv->state >= NM_DEVICE_STATE_UNAVAILABLE); if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) { nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED, NM_DEVICE_STATE_REASON_CARRIER); } else if (priv->state == NM_DEVICE_STATE_DISCONNECTED) { /* If the device is already in DISCONNECTED state without a carrier * (probably because it is tagged for carrier ignore) ensure that * when the carrier appears, auto connections are rechecked for * the device. */ nm_device_emit_recheck_auto_activate (self); } } else { g_return_if_fail (priv->state >= NM_DEVICE_STATE_UNAVAILABLE); if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) { if (nm_device_queued_state_peek (self) >= NM_DEVICE_STATE_DISCONNECTED) nm_device_queued_state_clear (self); } else { nm_device_queue_state (self, NM_DEVICE_STATE_UNAVAILABLE, NM_DEVICE_STATE_REASON_CARRIER); } } } #define LINK_DISCONNECT_DELAY 4 static gboolean link_disconnect_action_cb (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); _LOGD (LOGD_DEVICE, "link disconnected (calling deferred action) (id=%u)", priv->carrier_defer_id); priv->carrier_defer_id = 0; _LOGI (LOGD_DEVICE, "link disconnected (calling deferred action)"); NM_DEVICE_GET_CLASS (self)->carrier_changed (self, FALSE); return FALSE; } static void link_disconnect_action_cancel (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->carrier_defer_id) { g_source_remove (priv->carrier_defer_id); _LOGD (LOGD_DEVICE, "link disconnected (canceling deferred action) (id=%u)", priv->carrier_defer_id); priv->carrier_defer_id = 0; } } void nm_device_set_carrier (NMDevice *self, gboolean carrier) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDeviceState state = nm_device_get_state (self); if (priv->carrier == carrier) return; priv->carrier = carrier; g_object_notify (G_OBJECT (self), NM_DEVICE_CARRIER); if (priv->carrier) { _LOGI (LOGD_DEVICE, "link connected"); link_disconnect_action_cancel (self); klass->carrier_changed (self, TRUE); if (priv->carrier_wait_id) { g_source_remove (priv->carrier_wait_id); priv->carrier_wait_id = 0; nm_device_remove_pending_action (self, "carrier wait", TRUE); _carrier_wait_check_queued_act_request (self); } } else if (state <= NM_DEVICE_STATE_DISCONNECTED) { _LOGI (LOGD_DEVICE, "link disconnected"); klass->carrier_changed (self, FALSE); } else { _LOGI (LOGD_DEVICE, "link disconnected (deferring action for %d seconds)", LINK_DISCONNECT_DELAY); priv->carrier_defer_id = g_timeout_add_seconds (LINK_DISCONNECT_DELAY, link_disconnect_action_cb, self); _LOGD (LOGD_DEVICE, "link disconnected (deferring action for %d seconds) (id=%u)", LINK_DISCONNECT_DELAY, priv->carrier_defer_id); } } static void update_for_ip_ifname_change (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_hash_table_remove_all (priv->ip6_saved_properties); if (priv->dhcp4_client) { if (!nm_device_dhcp4_renew (self, FALSE)) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); return; } } if (priv->dhcp6_client) { if (!nm_device_dhcp6_renew (self, FALSE)) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); return; } } if (priv->rdisc) { /* FIXME: todo */ } if (priv->dnsmasq_manager) { /* FIXME: todo */ } } static void device_set_master (NMDevice *self, int ifindex) { NMDevice *master; NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); master = nm_manager_get_device_by_ifindex (nm_manager_get (), ifindex); if (master && NM_DEVICE_GET_CLASS (master)->enslave_slave) { g_clear_object (&priv->master); priv->master = g_object_ref (master); nm_device_master_add_slave (master, self, FALSE); } else if (master) { _LOGI (LOGD_DEVICE, "enslaved to non-master-type device %s; ignoring", nm_device_get_iface (master)); } else { _LOGW (LOGD_DEVICE, "enslaved to unknown device %d %s", ifindex, nm_platform_link_get_name (ifindex)); } } static void device_link_changed (NMDevice *self, NMPlatformLink *info) { NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMUtilsIPv6IfaceId token_iid; gboolean ip_ifname_changed = FALSE; if (info->udi && g_strcmp0 (info->udi, priv->udi)) { /* Update UDI to what udev gives us */ g_free (priv->udi); priv->udi = g_strdup (info->udi); g_object_notify (G_OBJECT (self), NM_DEVICE_UDI); } /* Update MTU if it has changed. */ if (priv->mtu != info->mtu) { priv->mtu = info->mtu; g_object_notify (G_OBJECT (self), NM_DEVICE_MTU); } if (info->name[0] && strcmp (priv->iface, info->name) != 0) { _LOGI (LOGD_DEVICE, "interface index %d renamed iface from '%s' to '%s'", priv->ifindex, priv->iface, info->name); g_free (priv->iface); priv->iface = g_strdup (info->name); /* If the device has no explicit ip_iface, then changing iface changes ip_iface too. */ ip_ifname_changed = !priv->ip_iface; g_object_notify (G_OBJECT (self), NM_DEVICE_IFACE); if (ip_ifname_changed) g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); /* Re-match available connections against the new interface name */ nm_device_recheck_available_connections (self); /* Let any connections that use the new interface name have a chance * to auto-activate on the device. */ nm_device_emit_recheck_auto_activate (self); } /* Update slave status for external changes */ if (priv->enslaved && info->master != nm_device_get_ifindex (priv->master)) nm_device_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_NONE); if (info->master && !priv->enslaved) { device_set_master (self, info->master); if (priv->master) nm_device_enslave_slave (priv->master, self, NULL); } if (priv->rdisc && nm_platform_link_get_ipv6_token (priv->ifindex, &token_iid)) { _LOGD (LOGD_DEVICE, "IPv6 tokenized identifier present on device %s", priv->iface); if (nm_rdisc_set_iid (priv->rdisc, token_iid)) nm_rdisc_start (priv->rdisc); } if (klass->link_changed) klass->link_changed (self, info); /* Update DHCP, etc, if needed */ if (ip_ifname_changed) update_for_ip_ifname_change (self); if (priv->up != info->up) { priv->up = info->up; /* Manage externally-created software interfaces only when they are IFF_UP */ g_assert (priv->ifindex > 0); if (is_software_external (self)) { gboolean external_down = nm_device_get_unmanaged_flag (self, NM_UNMANAGED_EXTERNAL_DOWN); if (external_down && info->up) { if (nm_device_get_state (self) < NM_DEVICE_STATE_DISCONNECTED) { /* Ensure the assume check is queued before any queued state changes * from the transition to UNAVAILABLE. */ nm_device_queue_recheck_assume (self); /* Resetting the EXTERNAL_DOWN flag may change the device's state * to UNAVAILABLE. To ensure that the state change doesn't touch * the device before assumption occurs, pass * NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED as the reason. */ nm_device_set_unmanaged (self, NM_UNMANAGED_EXTERNAL_DOWN, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED); } else { /* Don't trigger a state change; if the device is in a * state higher than UNAVAILABLE, it is already IFF_UP * or an explicit activation request was received. */ priv->unmanaged_flags &= ~NM_UNMANAGED_EXTERNAL_DOWN; } } else if (!external_down && !info->up && nm_device_get_state (self) <= NM_DEVICE_STATE_DISCONNECTED) { /* If the device is already disconnected and is set !IFF_UP, * unmanage it. */ nm_device_set_unmanaged (self, NM_UNMANAGED_EXTERNAL_DOWN, TRUE, NM_DEVICE_STATE_REASON_USER_REQUESTED); } } } } static void device_ip_link_changed (NMDevice *self, NMPlatformLink *info) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (info->name[0] && g_strcmp0 (priv->ip_iface, info->name)) { _LOGI (LOGD_DEVICE, "interface index %d renamed ip_iface (%d) from '%s' to '%s'", priv->ifindex, nm_device_get_ip_ifindex (self), priv->ip_iface, info->name); g_free (priv->ip_iface); priv->ip_iface = g_strdup (info->name); g_object_notify (G_OBJECT (self), NM_DEVICE_IP_IFACE); update_for_ip_ifname_change (self); } } static void link_changed_cb (NMPlatform *platform, int ifindex, NMPlatformLink *info, NMPlatformSignalChangeType change_type, NMPlatformReason reason, NMDevice *self) { if (change_type != NM_PLATFORM_SIGNAL_CHANGED) return; /* We don't filter by 'reason' because we are interested in *all* link * changes. For example a call to nm_platform_link_set_up() may result * in an internal carrier change (i.e. we ask the kernel to set IFF_UP * and it results in also setting IFF_LOWER_UP. */ if (ifindex == nm_device_get_ifindex (self)) device_link_changed (self, info); else if (ifindex == nm_device_get_ip_ifindex (self)) device_ip_link_changed (self, info); } static void link_changed (NMDevice *self, NMPlatformLink *info) { /* Update carrier from link event if applicable. */ if ( device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT) && !device_has_capability (self, NM_DEVICE_CAP_NONSTANDARD_CARRIER)) nm_device_set_carrier (self, info->connected); } /** * nm_device_notify_component_added(): * @self: the #NMDevice * @component: the component being added by a plugin * * Called by the manager to notify the device that a new component has * been found. The device implementation should return %TRUE if it * wishes to claim the component, or %FALSE if it cannot. * * Returns: %TRUE to claim the component, %FALSE if the component cannot be * claimed. */ gboolean nm_device_notify_component_added (NMDevice *self, GObject *component) { if (NM_DEVICE_GET_CLASS (self)->component_added) return NM_DEVICE_GET_CLASS (self)->component_added (self, component); return FALSE; } /** * nm_device_owns_iface(): * @self: the #NMDevice * @iface: an interface name * * Called by the manager to ask if the device or any of its components owns * @iface. For example, a WWAN implementation would return %TRUE for an * ethernet interface name that was owned by the WWAN device's modem component, * because that ethernet interface is controlled by the WWAN device and cannot * be used independently of the WWAN device. * * Returns: %TRUE if @self or it's components owns the interface name, * %FALSE if not */ gboolean nm_device_owns_iface (NMDevice *self, const char *iface) { if (NM_DEVICE_GET_CLASS (self)->owns_iface) return NM_DEVICE_GET_CLASS (self)->owns_iface (self, iface); return FALSE; } NMConnection * nm_device_new_default_connection (NMDevice *self) { if (NM_DEVICE_GET_CLASS (self)->new_default_connection) return NM_DEVICE_GET_CLASS (self)->new_default_connection (self); return NULL; } static void slave_state_changed (NMDevice *slave, NMDeviceState slave_new_state, NMDeviceState slave_old_state, NMDeviceStateReason reason, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); gboolean release = FALSE; _LOGD (LOGD_DEVICE, "slave %s state change %d (%s) -> %d (%s)", nm_device_get_iface (slave), slave_old_state, state_to_string (slave_old_state), slave_new_state, state_to_string (slave_new_state)); /* Don't try to enslave slaves until the master is ready */ if (priv->state < NM_DEVICE_STATE_CONFIG) return; if (slave_new_state == NM_DEVICE_STATE_IP_CONFIG) nm_device_enslave_slave (self, slave, nm_device_get_connection (slave)); else if (slave_new_state > NM_DEVICE_STATE_ACTIVATED) release = TRUE; else if ( slave_new_state <= NM_DEVICE_STATE_DISCONNECTED && slave_old_state > NM_DEVICE_STATE_DISCONNECTED) { /* Catch failures due to unavailable or unmanaged */ release = TRUE; } if (release) { nm_device_release_one_slave (self, slave, TRUE, reason); /* Bridge/bond/team interfaces are left up until manually deactivated */ if (priv->slaves == NULL && priv->state == NM_DEVICE_STATE_ACTIVATED) _LOGD (LOGD_DEVICE, "last slave removed; remaining activated"); } } /** * nm_device_master_add_slave: * @self: the master device * @slave: the slave device to enslave * @configure: pass %TRUE if the slave should be configured by the master, or * %FALSE if it is already configured outside NetworkManager * * If @self is capable of enslaving other devices (ie it's a bridge, bond, team, * etc) then this function adds @slave to the slave list for later enslavement. * * Returns: %TRUE on success, %FALSE on failure */ static gboolean nm_device_master_add_slave (NMDevice *self, NMDevice *slave, gboolean configure) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); SlaveInfo *info; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (slave != NULL, FALSE); g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE); if (configure) g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE); if (!find_slave_info (self, slave)) { info = g_malloc0 (sizeof (SlaveInfo)); info->slave = g_object_ref (slave); info->configure = configure; info->watch_id = g_signal_connect (slave, "state-changed", G_CALLBACK (slave_state_changed), self); priv->slaves = g_slist_append (priv->slaves, info); } nm_device_queue_recheck_assume (self); return TRUE; } /** * nm_device_master_get_slaves: * @self: the master device * * Returns: any slaves of which @self is the master. Caller owns returned list. */ GSList * nm_device_master_get_slaves (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); GSList *slaves = NULL, *iter; for (iter = priv->slaves; iter; iter = g_slist_next (iter)) slaves = g_slist_prepend (slaves, ((SlaveInfo *) iter->data)->slave); return slaves; } /** * nm_device_master_get_slave_by_ifindex: * @self: the master device * @ifindex: the slave's interface index * * Returns: the slave with the given @ifindex of which @self is the master, * or %NULL if no device with @ifindex is a slave of @self. */ NMDevice * nm_device_master_get_slave_by_ifindex (NMDevice *self, int ifindex) { GSList *iter; for (iter = NM_DEVICE_GET_PRIVATE (self)->slaves; iter; iter = g_slist_next (iter)) { SlaveInfo *info = iter->data; if (nm_device_get_ip_ifindex (info->slave) == ifindex) return info->slave; } return NULL; } /** * nm_device_master_check_slave_physical_port: * @self: the master device * @slave: a slave device * @log_domain: domain to log a warning in * * Checks if @self already has a slave with the same #NMDevice:physical-port-id * as @slave, and logs a warning if so. */ void nm_device_master_check_slave_physical_port (NMDevice *self, NMDevice *slave, guint64 log_domain) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *slave_physical_port_id, *existing_physical_port_id; SlaveInfo *info; GSList *iter; slave_physical_port_id = nm_device_get_physical_port_id (slave); if (!slave_physical_port_id) return; for (iter = priv->slaves; iter; iter = iter->next) { info = iter->data; if (info->slave == slave) continue; existing_physical_port_id = nm_device_get_physical_port_id (info->slave); if (!g_strcmp0 (slave_physical_port_id, existing_physical_port_id)) { _LOGW (log_domain, "slave %s shares a physical port with existing slave %s", nm_device_get_ip_iface (slave), nm_device_get_ip_iface (info->slave)); /* Since this function will get called for every slave, we only have * to warn about the first match we find; if there are other matches * later in the list, we will have already warned about them matching * @existing earlier. */ return; } } } /* release all slaves */ static void nm_device_master_release_slaves (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceStateReason reason; /* Don't release the slaves if this connection doesn't belong to NM. */ if (nm_device_uses_generated_assumed_connection (self)) return; reason = priv->state_reason; if (priv->state == NM_DEVICE_STATE_FAILED) reason = NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED; while (priv->slaves) { SlaveInfo *info = priv->slaves->data; nm_device_release_one_slave (self, info->slave, TRUE, reason); } } /** * nm_device_get_master: * @self: the device * * If @self has been enslaved by another device, this returns that * device. Otherwise it returns %NULL. (In particular, note that if * @self is in the process of activating as a slave, but has not yet * been enslaved by its master, this will return %NULL.) * * Returns: (transfer none): @self's master, or %NULL */ NMDevice * nm_device_get_master (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->enslaved) return priv->master; else return NULL; } /** * nm_device_slave_notify_enslave: * @self: the slave device * @success: whether the enslaving operation succeeded * * Notifies a slave that either it has been enslaved, or else its master tried * to enslave it and failed. */ static void nm_device_slave_notify_enslave (NMDevice *self, gboolean success) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = nm_device_get_connection (self); gboolean activating = (priv->state == NM_DEVICE_STATE_IP_CONFIG); g_assert (priv->master); if (!priv->enslaved) { if (success) { if (activating) { _LOGI (LOGD_DEVICE, "Activation: connection '%s' enslaved, continuing activation", nm_connection_get_id (connection)); } else _LOGI (LOGD_DEVICE, "enslaved to %s", nm_device_get_iface (priv->master)); priv->enslaved = TRUE; g_object_notify (G_OBJECT (self), NM_DEVICE_MASTER); } else if (activating) { _LOGW (LOGD_DEVICE, "Activation: connection '%s' could not be enslaved", nm_connection_get_id (connection)); } } if (activating) { priv->ip4_state = IP_DONE; priv->ip6_state = IP_DONE; nm_device_queue_state (self, success ? NM_DEVICE_STATE_SECONDARIES : NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_NONE); } else nm_device_queue_recheck_assume (self); } /** * nm_device_slave_notify_release: * @self: the slave device * @reason: the reason associated with the state change * * Notifies a slave that it has been released, and why. */ static void nm_device_slave_notify_release (NMDevice *self, NMDeviceStateReason reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = nm_device_get_connection (self); NMDeviceState new_state; const char *master_status; if ( reason != NM_DEVICE_STATE_REASON_NONE && priv->state > NM_DEVICE_STATE_DISCONNECTED && priv->state <= NM_DEVICE_STATE_ACTIVATED) { if (reason == NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED) { new_state = NM_DEVICE_STATE_FAILED; master_status = "failed"; } else if (reason == NM_DEVICE_STATE_REASON_USER_REQUESTED) { new_state = NM_DEVICE_STATE_DEACTIVATING; master_status = "deactivated by user request"; } else { new_state = NM_DEVICE_STATE_DISCONNECTED; master_status = "deactivated"; } _LOGD (LOGD_DEVICE, "Activation: connection '%s' master %s", nm_connection_get_id (connection), master_status); nm_device_queue_state (self, new_state, reason); } else if (priv->master) _LOGI (LOGD_DEVICE, "released from master %s", nm_device_get_iface (priv->master)); else _LOGD (LOGD_DEVICE, "released from master%s", priv->enslaved ? "" : " (was not enslaved)"); if (priv->enslaved) { priv->enslaved = FALSE; g_object_notify (G_OBJECT (self), NM_DEVICE_MASTER); } } /** * nm_device_get_enslaved: * @self: the #NMDevice * * Returns: %TRUE if the device is enslaved to a master device (eg bridge or * bond or team), %FALSE if not */ gboolean nm_device_get_enslaved (NMDevice *self) { return NM_DEVICE_GET_PRIVATE (self)->enslaved; } /** * nm_device_removed: * @self: the #NMDevice * * Called by the manager when the device was removed. Releases the device from * the master in case it's enslaved. */ void nm_device_removed (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->enslaved) nm_device_release_one_slave (priv->master, self, FALSE, NM_DEVICE_STATE_REASON_REMOVED); } static gboolean is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->carrier || priv->ignore_carrier) return TRUE; if (NM_FLAGS_HAS (flags, NM_DEVICE_CHECK_DEV_AVAILABLE_IGNORE_CARRIER)) return TRUE; return FALSE; } /** * nm_device_is_available: * @self: the #NMDevice * @flags: additional flags to influence the check. Flags have the * meaning to increase the availability of a device. * * Checks if @self would currently be capable of activating a * connection. In particular, it checks that the device is ready (eg, * is not missing firmware), that it has carrier (if necessary), and * that any necessary external software (eg, ModemManager, * wpa_supplicant) is available. * * @self can only be in a state higher than * %NM_DEVICE_STATE_UNAVAILABLE when nm_device_is_available() returns * %TRUE. (But note that it can still be %NM_DEVICE_STATE_UNMANAGED * when it is available.) * * Returns: %TRUE or %FALSE */ gboolean nm_device_is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->firmware_missing) return FALSE; return NM_DEVICE_GET_CLASS (self)->is_available (self, flags); } gboolean nm_device_get_enabled (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); if (NM_DEVICE_GET_CLASS (self)->get_enabled) return NM_DEVICE_GET_CLASS (self)->get_enabled (self); return TRUE; } void nm_device_set_enabled (NMDevice *self, gboolean enabled) { g_return_if_fail (NM_IS_DEVICE (self)); if (NM_DEVICE_GET_CLASS (self)->set_enabled) NM_DEVICE_GET_CLASS (self)->set_enabled (self, enabled); } /** * nm_device_get_autoconnect: * @self: the #NMDevice * * Returns: %TRUE if the device allows autoconnect connections, or %FALSE if the * device is explicitly blocking all autoconnect connections. Does not take * into account transient conditions like companion devices that may wish to * block the device. */ gboolean nm_device_get_autoconnect (NMDevice *self) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); return NM_DEVICE_GET_PRIVATE (self)->autoconnect; } static void nm_device_set_autoconnect (NMDevice *self, gboolean autoconnect) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); if (priv->autoconnect == autoconnect) return; if (autoconnect) { /* Default-unmanaged devices never autoconnect */ if (!nm_device_get_default_unmanaged (self)) { priv->autoconnect = TRUE; g_object_notify (G_OBJECT (self), NM_DEVICE_AUTOCONNECT); } } else { priv->autoconnect = FALSE; g_object_notify (G_OBJECT (self), NM_DEVICE_AUTOCONNECT); } } static gboolean autoconnect_allowed_accumulator (GSignalInvocationHint *ihint, GValue *return_accu, const GValue *handler_return, gpointer data) { if (!g_value_get_boolean (handler_return)) g_value_set_boolean (return_accu, FALSE); return TRUE; } /** * nm_device_autoconnect_allowed: * @self: the #NMDevice * * Returns: %TRUE if the device can be auto-connected immediately, taking * transient conditions into account (like companion devices that may wish to * block autoconnect for a time). */ gboolean nm_device_autoconnect_allowed (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); GValue instance = G_VALUE_INIT; GValue retval = G_VALUE_INIT; if (priv->state < NM_DEVICE_STATE_DISCONNECTED || !priv->autoconnect) return FALSE; /* The 'autoconnect-allowed' signal is emitted on a device to allow * other listeners to block autoconnect on the device if they wish. * This is mainly used by the OLPC Mesh devices to block autoconnect * on their companion WiFi device as they share radio resources and * cannot be connected at the same time. */ g_value_init (&instance, G_TYPE_OBJECT); g_value_set_object (&instance, self); g_value_init (&retval, G_TYPE_BOOLEAN); if (priv->autoconnect) g_value_set_boolean (&retval, TRUE); else g_value_set_boolean (&retval, FALSE); /* Use g_signal_emitv() rather than g_signal_emit() to avoid the return * value being changed if no handlers are connected */ g_signal_emitv (&instance, signals[AUTOCONNECT_ALLOWED], 0, &retval); g_value_unset (&instance); return g_value_get_boolean (&retval); } static gboolean can_auto_connect (NMDevice *self, NMConnection *connection, char **specific_object) { NMSettingConnection *s_con; s_con = nm_connection_get_setting_connection (connection); if (!nm_setting_connection_get_autoconnect (s_con)) return FALSE; return nm_device_check_connection_available (self, connection, NM_DEVICE_CHECK_CON_AVAILABLE_NONE, NULL); } /** * nm_device_can_auto_connect: * @self: an #NMDevice * @connection: a #NMConnection * @specific_object: (out) (transfer full): on output, the path of an * object associated with the returned connection, to be passed to * nm_manager_activate_connection(), or %NULL. * * Checks if @connection can be auto-activated on @self right now. * This requires, at a minimum, that the connection be compatible with * @self, and that it have the #NMSettingConnection:autoconnect property * set, and that the device allow auto connections. Some devices impose * additional requirements. (Eg, a Wi-Fi connection can only be activated * if its SSID was seen in the last scan.) * * Returns: %TRUE, if the @connection can be auto-activated. **/ gboolean nm_device_can_auto_connect (NMDevice *self, NMConnection *connection, char **specific_object) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE); g_return_val_if_fail (specific_object && !*specific_object, FALSE); if (nm_device_autoconnect_allowed (self)) return NM_DEVICE_GET_CLASS (self)->can_auto_connect (self, connection, specific_object); return FALSE; } static gboolean device_has_config (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); /* Check for IP configuration. */ if (priv->ip4_config && nm_ip4_config_get_num_addresses (priv->ip4_config)) return TRUE; if (priv->ip6_config && nm_ip6_config_get_num_addresses (priv->ip6_config)) return TRUE; /* The existence of a software device is good enough. */ if (nm_device_is_software (self)) return TRUE; /* Slaves are also configured by definition */ if (nm_platform_link_get_master (priv->ifindex) > 0) return TRUE; return FALSE; } /** * nm_device_master_update_slave_connection: * @self: the master #NMDevice * @slave: the slave #NMDevice * @connection: the #NMConnection to update with the slave settings * @GError: (out): error description * * Reads the slave configuration for @slave and updates @connection with those * properties. This invokes a virtual function on the master device @self. * * Returns: %TRUE if the configuration was read and @connection updated, * %FALSE on failure. */ gboolean nm_device_master_update_slave_connection (NMDevice *self, NMDevice *slave, NMConnection *connection, GError **error) { NMDeviceClass *klass; gboolean success; g_return_val_if_fail (self, FALSE); g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (slave, FALSE); g_return_val_if_fail (connection, FALSE); g_return_val_if_fail (!error || !*error, FALSE); g_return_val_if_fail (nm_connection_get_setting_connection (connection), FALSE); g_return_val_if_fail (nm_device_get_iface (self), FALSE); klass = NM_DEVICE_GET_CLASS (self); if (klass->master_update_slave_connection) { success = klass->master_update_slave_connection (self, slave, connection, error); g_return_val_if_fail (!error || (success && !*error) || *error, success); return success; } g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED, "master device '%s' cannot update a slave connection for slave device '%s' (master type not supported?)", nm_device_get_iface (self), nm_device_get_iface (slave)); return FALSE; } NMConnection * nm_device_generate_connection (NMDevice *self, NMDevice *master) { NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *ifname = nm_device_get_iface (self); NMConnection *connection; NMSetting *s_con; NMSetting *s_ip4; NMSetting *s_ip6; gs_free char *uuid = NULL; const char *ip4_method, *ip6_method; GError *error = NULL; /* If update_connection() is not implemented, just fail. */ if (!klass->update_connection) return NULL; /* Return NULL if device is unconfigured. */ if (!device_has_config (self)) { _LOGD (LOGD_DEVICE, "device has no existing configuration"); return NULL; } connection = nm_simple_connection_new (); s_con = nm_setting_connection_new (); uuid = nm_utils_uuid_generate (); g_object_set (s_con, NM_SETTING_CONNECTION_UUID, uuid, NM_SETTING_CONNECTION_ID, ifname, NM_SETTING_CONNECTION_AUTOCONNECT, FALSE, NM_SETTING_CONNECTION_INTERFACE_NAME, ifname, NM_SETTING_CONNECTION_TIMESTAMP, (guint64) time (NULL), NULL); if (klass->connection_type) g_object_set (s_con, NM_SETTING_CONNECTION_TYPE, klass->connection_type, NULL); nm_connection_add_setting (connection, s_con); /* If the device is a slave, update various slave settings */ if (master) { if (!nm_device_master_update_slave_connection (master, self, connection, &error)) { _LOGE (LOGD_DEVICE, "master device '%s' failed to update slave connection: %s", nm_device_get_iface (master), error ? error->message : "(unknown error)"); g_error_free (error); g_object_unref (connection); return NULL; } } else { /* Only regular and master devices get IP configuration; slaves do not */ s_ip4 = nm_ip4_config_create_setting (priv->ip4_config); nm_connection_add_setting (connection, s_ip4); s_ip6 = nm_ip6_config_create_setting (priv->ip6_config); nm_connection_add_setting (connection, s_ip6); } klass->update_connection (self, connection); /* Check the connection in case of update_connection() bug. */ if (!nm_connection_verify (connection, &error)) { _LOGE (LOGD_DEVICE, "Generated connection does not verify: %s", error->message); g_clear_error (&error); g_object_unref (connection); return NULL; } /* Ignore the connection if it has no IP configuration, * no slave configuration, and is not a master interface. */ ip4_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); ip6_method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); if ( g_strcmp0 (ip4_method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0 && g_strcmp0 (ip6_method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE) == 0 && !nm_setting_connection_get_master (NM_SETTING_CONNECTION (s_con)) && !priv->slaves) { _LOGD (LOGD_DEVICE, "ignoring generated connection (no IP and not in master-slave relationship)"); g_object_unref (connection); connection = NULL; } return connection; } gboolean nm_device_complete_connection (NMDevice *self, NMConnection *connection, const char *specific_object, const GSList *existing_connections, GError **error) { gboolean success = FALSE; g_return_val_if_fail (self != NULL, FALSE); g_return_val_if_fail (connection != NULL, FALSE); if (!NM_DEVICE_GET_CLASS (self)->complete_connection) { g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_INVALID_CONNECTION, "Device class %s had no complete_connection method", G_OBJECT_TYPE_NAME (self)); return FALSE; } success = NM_DEVICE_GET_CLASS (self)->complete_connection (self, connection, specific_object, existing_connections, error); if (success) success = nm_connection_verify (connection, error); return success; } static gboolean check_connection_compatible (NMDevice *self, NMConnection *connection) { NMSettingConnection *s_con; const char *config_iface, *device_iface; s_con = nm_connection_get_setting_connection (connection); g_assert (s_con); config_iface = nm_setting_connection_get_interface_name (s_con); device_iface = nm_device_get_iface (self); if (config_iface && strcmp (config_iface, device_iface) != 0) return FALSE; return TRUE; } /** * nm_device_check_connection_compatible: * @self: an #NMDevice * @connection: an #NMConnection * * Checks if @connection could potentially be activated on @self. * This means only that @self has the proper capabilities, and that * @connection is not locked to some other device. It does not * necessarily mean that @connection could be activated on @self * right now. (Eg, it might refer to a Wi-Fi network that is not * currently available.) * * Returns: #TRUE if @connection could potentially be activated on * @self. */ gboolean nm_device_check_connection_compatible (NMDevice *self, NMConnection *connection) { g_return_val_if_fail (NM_IS_DEVICE (self), FALSE); g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE); return NM_DEVICE_GET_CLASS (self)->check_connection_compatible (self, connection); } /** * nm_device_can_assume_connections: * @self: #NMDevice instance * * This is a convenience function to determine whether connection assumption * is available for this device. * * Returns: %TRUE if the device is capable of assuming connections, %FALSE if not */ static gboolean nm_device_can_assume_connections (NMDevice *self) { return !!NM_DEVICE_GET_CLASS (self)->update_connection; } /** * nm_device_can_assume_active_connection: * @self: #NMDevice instance * * This is a convenience function to determine whether the device's active * connection can be assumed if NetworkManager restarts. This method returns * %TRUE if and only if the device can assume connections, and the device has * an active connection, and that active connection can be assumed. * * Returns: %TRUE if the device's active connection can be assumed, or %FALSE * if there is no active connection or the active connection cannot be * assumed. */ gboolean nm_device_can_assume_active_connection (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; const char *assumable_ip6_methods[] = { NM_SETTING_IP6_CONFIG_METHOD_IGNORE, NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_DHCP, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL, NM_SETTING_IP6_CONFIG_METHOD_MANUAL, NULL }; const char *assumable_ip4_methods[] = { NM_SETTING_IP4_CONFIG_METHOD_DISABLED, NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_MANUAL, NULL }; if (!nm_device_can_assume_connections (self)) return FALSE; connection = nm_device_get_connection (self); if (!connection) return FALSE; /* Can't assume connections that aren't yet configured * FIXME: what about bridges/bonds waiting for slaves? */ if (priv->state < NM_DEVICE_STATE_IP_CONFIG) return FALSE; if (priv->ip4_state != IP_DONE && priv->ip6_state != IP_DONE) return FALSE; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); if (!_nm_utils_string_in_list (method, assumable_ip6_methods)) return FALSE; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); if (!_nm_utils_string_in_list (method, assumable_ip4_methods)) return FALSE; return TRUE; } static gboolean nm_device_emit_recheck_assume (gpointer self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); priv->recheck_assume_id = 0; if (!nm_device_get_act_request (self)) { _LOGD (LOGD_DEVICE, "emit RECHECK_ASSUME signal"); g_signal_emit (self, signals[RECHECK_ASSUME], 0); } return G_SOURCE_REMOVE; } void nm_device_queue_recheck_assume (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (nm_device_can_assume_connections (self) && !priv->recheck_assume_id) priv->recheck_assume_id = g_idle_add (nm_device_emit_recheck_assume, self); } void nm_device_emit_recheck_auto_activate (NMDevice *self) { g_signal_emit (self, signals[RECHECK_AUTO_ACTIVATE], 0); } static void dnsmasq_state_changed_cb (NMDnsMasqManager *manager, guint32 status, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); switch (status) { case NM_DNSMASQ_STATUS_DEAD: nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_SHARED_START_FAILED); break; default: break; } } static void activation_source_clear (NMDevice *self, gboolean remove_source, int family) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); guint *act_source_id; gpointer *act_source_func; if (family == AF_INET6) { act_source_id = &priv->act_source6_id; act_source_func = &priv->act_source6_func; } else { act_source_id = &priv->act_source_id; act_source_func = &priv->act_source_func; } if (*act_source_id) { if (remove_source) g_source_remove (*act_source_id); *act_source_id = 0; *act_source_func = NULL; } } static void activation_source_schedule (NMDevice *self, GSourceFunc func, int family) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); guint *act_source_id; gpointer *act_source_func; if (family == AF_INET6) { act_source_id = &priv->act_source6_id; act_source_func = &priv->act_source6_func; } else { act_source_id = &priv->act_source_id; act_source_func = &priv->act_source_func; } if (*act_source_id) _LOGE (LOGD_DEVICE, "activation stage already scheduled"); /* Don't bother rescheduling the same function that's about to * run anyway. Fixes issues with crappy wireless drivers sending * streams of associate events before NM has had a chance to process * the first one. */ if (!*act_source_id || (*act_source_func != func)) { activation_source_clear (self, TRUE, family); *act_source_id = g_idle_add (func, self); *act_source_func = func; } } static gboolean get_ip_config_may_fail (NMDevice *self, int family) { NMConnection *connection; NMSettingIPConfig *s_ip = NULL; g_return_val_if_fail (self != NULL, TRUE); connection = nm_device_get_connection (self); g_assert (connection); /* Fail the connection if the failed IP method is required to complete */ switch (family) { case AF_INET: s_ip = nm_connection_get_setting_ip4_config (connection); break; case AF_INET6: s_ip = nm_connection_get_setting_ip6_config (connection); break; default: g_assert_not_reached (); } return nm_setting_ip_config_get_may_fail (s_ip); } static void master_ready_cb (NMActiveConnection *active, GParamSpec *pspec, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActiveConnection *master; g_assert (priv->state == NM_DEVICE_STATE_PREPARE); /* Notify a master device that it has a new slave */ g_assert (nm_active_connection_get_master_ready (active)); master = nm_active_connection_get_master (active); priv->master = g_object_ref (nm_active_connection_get_device (master)); nm_device_master_add_slave (priv->master, self, nm_active_connection_get_assumed (active) ? FALSE : TRUE); _LOGD (LOGD_DEVICE, "master connection ready; master device %s", nm_device_get_iface (priv->master)); if (priv->master_ready_id) { g_signal_handler_disconnect (active, priv->master_ready_id); priv->master_ready_id = 0; } nm_device_activate_schedule_stage2_device_config (self); } static NMActStageReturn act_stage1_prepare (NMDevice *self, NMDeviceStateReason *reason) { return NM_ACT_STAGE_RETURN_SUCCESS; } /* * nm_device_activate_stage1_device_prepare * * Prepare for device activation * */ static gboolean nm_device_activate_stage1_device_prepare (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret = NM_ACT_STAGE_RETURN_SUCCESS; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request); /* Clear the activation source ID now that this stage has run */ activation_source_clear (self, FALSE, 0); priv->ip4_state = priv->ip6_state = IP_NONE; /* Notify the new ActiveConnection along with the state change */ g_object_notify (G_OBJECT (self), NM_DEVICE_ACTIVE_CONNECTION); _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) started..."); nm_device_state_changed (self, NM_DEVICE_STATE_PREPARE, NM_DEVICE_STATE_REASON_NONE); /* Assumed connections were already set up outside NetworkManager */ if (!nm_active_connection_get_assumed (active)) { ret = NM_DEVICE_GET_CLASS (self)->act_stage1_prepare (self, &reason); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) { goto out; } else if (ret == NM_ACT_STAGE_RETURN_FAILURE) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); goto out; } g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } if (nm_active_connection_get_master (active)) { /* If the master connection is ready for slaves, attach ourselves */ if (nm_active_connection_get_master_ready (active)) master_ready_cb (active, NULL, self); else { _LOGD (LOGD_DEVICE, "waiting for master connection to become ready"); /* Attach a signal handler and wait for the master connection to begin activating */ g_assert (priv->master_ready_id == 0); priv->master_ready_id = g_signal_connect (active, "notify::" NM_ACTIVE_CONNECTION_INT_MASTER_READY, (GCallback) master_ready_cb, self); /* Postpone */ } } else nm_device_activate_schedule_stage2_device_config (self); out: _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) complete."); return FALSE; } /* * nm_device_activate_schedule_stage1_device_prepare * * Prepare a device for activation * */ void nm_device_activate_schedule_stage1_device_prepare (NMDevice *self) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->act_request); activation_source_schedule (self, nm_device_activate_stage1_device_prepare, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 1 of 5 (Device Prepare) scheduled..."); } static NMActStageReturn act_stage2_config (NMDevice *self, NMDeviceStateReason *reason) { /* Nothing to do */ return NM_ACT_STAGE_RETURN_SUCCESS; } /* * nm_device_activate_stage2_device_config * * Determine device parameters and set those on the device, ie * for wireless devices, set SSID, keys, etc. * */ static gboolean nm_device_activate_stage2_device_config (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; gboolean no_firmware = FALSE; NMActiveConnection *active = NM_ACTIVE_CONNECTION (priv->act_request); GSList *iter; /* Clear the activation source ID now that this stage has run */ activation_source_clear (self, FALSE, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) starting..."); nm_device_state_changed (self, NM_DEVICE_STATE_CONFIG, NM_DEVICE_STATE_REASON_NONE); /* Assumed connections were already set up outside NetworkManager */ if (!nm_active_connection_get_assumed (active)) { if (!nm_device_bring_up (self, FALSE, &no_firmware)) { if (no_firmware) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_FIRMWARE_MISSING); else nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_CONFIG_FAILED); goto out; } ret = NM_DEVICE_GET_CLASS (self)->act_stage2_config (self, &reason); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) goto out; else if (ret == NM_ACT_STAGE_RETURN_FAILURE) { nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); goto out; } g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } /* If we have slaves that aren't yet enslaved, do that now */ for (iter = priv->slaves; iter; iter = g_slist_next (iter)) { SlaveInfo *info = iter->data; NMDeviceState slave_state = nm_device_get_state (info->slave); if (slave_state == NM_DEVICE_STATE_IP_CONFIG) nm_device_enslave_slave (self, info->slave, nm_device_get_connection (info->slave)); else if ( nm_device_uses_generated_assumed_connection (self) && slave_state <= NM_DEVICE_STATE_DISCONNECTED) nm_device_queue_recheck_assume (info->slave); } _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) successful."); nm_device_activate_schedule_stage3_ip_config_start (self); out: _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) complete."); return FALSE; } /* * nm_device_activate_schedule_stage2_device_config * * Schedule setup of the hardware device * */ void nm_device_activate_schedule_stage2_device_config (NMDevice *self) { NMDevicePrivate *priv; g_return_if_fail (NM_IS_DEVICE (self)); priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (priv->act_request); activation_source_schedule (self, nm_device_activate_stage2_device_config, 0); _LOGI (LOGD_DEVICE, "Activation: Stage 2 of 5 (Device Configure) scheduled..."); } /*********************************************/ /* avahi-autoipd stuff */ static void aipd_timeout_remove (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_timeout) { g_source_remove (priv->aipd_timeout); priv->aipd_timeout = 0; } } static void aipd_cleanup (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_watch) { g_source_remove (priv->aipd_watch); priv->aipd_watch = 0; } if (priv->aipd_pid > 0) { nm_utils_kill_child_sync (priv->aipd_pid, SIGKILL, LOGD_AUTOIP4, "avahi-autoipd", NULL, 0, 0); priv->aipd_pid = -1; } aipd_timeout_remove (self); } static NMIP4Config * aipd_get_ip4_config (NMDevice *self, guint32 lla) { NMIP4Config *config = NULL; NMPlatformIP4Address address; NMPlatformIP4Route route; config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); g_assert (config); memset (&address, 0, sizeof (address)); address.address = lla; address.plen = 16; address.source = NM_IP_CONFIG_SOURCE_IP4LL; nm_ip4_config_add_address (config, &address); /* Add a multicast route for link-local connections: destination= 224.0.0.0, netmask=240.0.0.0 */ memset (&route, 0, sizeof (route)); route.network = htonl (0xE0000000L); route.plen = 4; route.source = NM_IP_CONFIG_SOURCE_IP4LL; route.metric = nm_device_get_ip4_route_metric (self); nm_ip4_config_add_route (config, &route); return config; } #define IPV4LL_NETWORK (htonl (0xA9FE0000L)) #define IPV4LL_NETMASK (htonl (0xFFFF0000L)) void nm_device_handle_autoip4_event (NMDevice *self, const char *event, const char *address) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection = NULL; const char *method; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; g_return_if_fail (event != NULL); if (priv->act_request == NULL) return; connection = nm_act_request_get_connection (priv->act_request); g_assert (connection); /* Ignore if the connection isn't an AutoIP connection */ method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); if (g_strcmp0 (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) != 0) return; if (strcmp (event, "BIND") == 0) { guint32 lla; NMIP4Config *config; if (inet_pton (AF_INET, address, &lla) <= 0) { _LOGE (LOGD_AUTOIP4, "invalid address %s received from avahi-autoipd.", address); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_ERROR); return; } if ((lla & IPV4LL_NETMASK) != IPV4LL_NETWORK) { _LOGE (LOGD_AUTOIP4, "invalid address %s received from avahi-autoipd (not link-local).", address); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_ERROR); return; } config = aipd_get_ip4_config (self, lla); if (config == NULL) { _LOGE (LOGD_AUTOIP4, "failed to get autoip config"); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE); return; } if (priv->ip4_state == IP_CONF) { aipd_timeout_remove (self); nm_device_activate_schedule_ip4_config_result (self, config); } else if (priv->ip4_state == IP_DONE) { if (!ip4_config_merge_and_apply (self, config, TRUE, &reason)) { _LOGE (LOGD_AUTOIP4, "failed to update IP4 config for autoip change."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } } else g_assert_not_reached (); g_object_unref (config); } else { _LOGW (LOGD_AUTOIP4, "autoip address %s no longer valid because '%s'.", address, event); /* The address is gone; terminate the connection or fail activation */ nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); } } static void aipd_watch_cb (GPid pid, gint status, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMDeviceState state; if (!priv->aipd_watch) return; priv->aipd_watch = 0; if (WIFEXITED (status)) _LOGD (LOGD_AUTOIP4, "avahi-autoipd exited with error code %d", WEXITSTATUS (status)); else if (WIFSTOPPED (status)) _LOGW (LOGD_AUTOIP4, "avahi-autoipd stopped unexpectedly with signal %d", WSTOPSIG (status)); else if (WIFSIGNALED (status)) _LOGW (LOGD_AUTOIP4, "avahi-autoipd died with signal %d", WTERMSIG (status)); else _LOGW (LOGD_AUTOIP4, "avahi-autoipd died from an unknown cause"); aipd_cleanup (self); state = nm_device_get_state (self); if (nm_device_is_activating (self) || (state == NM_DEVICE_STATE_ACTIVATED)) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_AUTOIP_FAILED); } static gboolean aipd_timeout_cb (gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->aipd_timeout) { _LOGI (LOGD_AUTOIP4, "avahi-autoipd timed out."); priv->aipd_timeout = 0; aipd_cleanup (self); if (priv->ip4_state == IP_CONF) nm_device_activate_schedule_ip4_config_timeout (self); } return FALSE; } /* default to installed helper, but can be modified for testing */ const char *nm_device_autoipd_helper_path = LIBEXECDIR "/nm-avahi-autoipd.action"; static NMActStageReturn aipd_start (NMDevice *self, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); const char *argv[6]; char *cmdline; const char *aipd_binary; int i = 0; GError *error = NULL; aipd_cleanup (self); /* Find avahi-autoipd */ aipd_binary = nm_utils_find_helper ("avahi-autoipd", NULL, NULL); if (!aipd_binary) { _LOGW (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) failed" " to start avahi-autoipd: not found"); *reason = NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED; return NM_ACT_STAGE_RETURN_FAILURE; } argv[i++] = aipd_binary; argv[i++] = "--script"; argv[i++] = nm_device_autoipd_helper_path; if (nm_logging_enabled (LOGL_DEBUG, LOGD_AUTOIP4)) argv[i++] = "--debug"; argv[i++] = nm_device_get_ip_iface (self); argv[i++] = NULL; cmdline = g_strjoinv (" ", (char **) argv); _LOGD (LOGD_AUTOIP4, "running: %s", cmdline); g_free (cmdline); if (!g_spawn_async ("/", (char **) argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, nm_utils_setpgid, NULL, &(priv->aipd_pid), &error)) { _LOGW (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) failed" " to start avahi-autoipd: %s", error && error->message ? error->message : "(unknown)"); g_clear_error (&error); aipd_cleanup (self); return NM_ACT_STAGE_RETURN_FAILURE; } _LOGI (LOGD_DEVICE | LOGD_AUTOIP4, "Activation: Stage 3 of 5 (IP Configure Start) started" " avahi-autoipd..."); /* Monitor the child process so we know when it dies */ priv->aipd_watch = g_child_watch_add (priv->aipd_pid, aipd_watch_cb, self); /* Start a timeout to bound the address attempt */ priv->aipd_timeout = g_timeout_add_seconds (20, aipd_timeout_cb, self); return NM_ACT_STAGE_RETURN_POSTPONE; } /*********************************************/ static gboolean _device_get_default_route_from_platform (NMDevice *self, int addr_family, NMPlatformIPRoute *out_route) { gboolean success = FALSE; int ifindex = nm_device_get_ip_ifindex (self); GArray *routes; if (addr_family == AF_INET) routes = nm_platform_ip4_route_get_all (ifindex, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT); else routes = nm_platform_ip6_route_get_all (ifindex, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT); if (routes) { guint route_metric = G_MAXUINT32, m; const NMPlatformIPRoute *route = NULL, *r; guint i; /* if there are several default routes, find the one with the best metric */ for (i = 0; i < routes->len; i++) { if (addr_family == AF_INET) { r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP4Route, i); m = r->metric; } else { r = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP6Route, i); m = nm_utils_ip6_route_metric_normalize (r->metric); } if (!route || m < route_metric) { route = r; route_metric = m; } } if (route) { if (addr_family == AF_INET) *((NMPlatformIP4Route *) out_route) = *((NMPlatformIP4Route *) route); else *((NMPlatformIP6Route *) out_route) = *((NMPlatformIP6Route *) route); success = TRUE; } g_array_free (routes, TRUE); } return success; } /*********************************************/ static void ensure_con_ipx_config (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); int ip_ifindex = nm_device_get_ip_ifindex (self); NMConnection *connection; g_assert (!!priv->con_ip4_config == !!priv->con_ip6_config); if (priv->con_ip4_config) return; connection = nm_device_get_connection (self); if (!connection) return; priv->con_ip4_config = nm_ip4_config_new (ip_ifindex); priv->con_ip6_config = nm_ip6_config_new (ip_ifindex); nm_ip4_config_merge_setting (priv->con_ip4_config, nm_connection_get_setting_ip4_config (connection), nm_device_get_ip4_route_metric (self)); nm_ip6_config_merge_setting (priv->con_ip6_config, nm_connection_get_setting_ip6_config (connection), nm_device_get_ip6_route_metric (self)); if (nm_device_uses_assumed_connection (self)) { /* For assumed connections ignore all addresses and routes. */ nm_ip4_config_reset_addresses (priv->con_ip4_config); nm_ip4_config_reset_routes (priv->con_ip4_config); nm_ip6_config_reset_addresses (priv->con_ip6_config); nm_ip6_config_reset_routes (priv->con_ip6_config); } } /*********************************************/ /* DHCPv4 stuff */ static void dhcp4_cleanup (NMDevice *self, gboolean stop, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->dhcp4_client) { /* Stop any ongoing DHCP transaction on this device */ if (priv->dhcp4_state_sigid) { g_signal_handler_disconnect (priv->dhcp4_client, priv->dhcp4_state_sigid); priv->dhcp4_state_sigid = 0; } nm_device_remove_pending_action (self, PENDING_ACTION_DHCP4, FALSE); if (stop) nm_dhcp_client_stop (priv->dhcp4_client, release); g_clear_object (&priv->dhcp4_client); } if (priv->dhcp4_config) { g_clear_object (&priv->dhcp4_config); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP4_CONFIG); } } static gboolean ip4_config_merge_and_apply (NMDevice *self, NMIP4Config *config, gboolean commit, NMDeviceStateReason *out_reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; gboolean success; NMIP4Config *composite; gboolean has_direct_route; const guint32 default_route_metric = nm_device_get_ip4_route_metric (self); guint32 gateway; /* Merge all the configs into the composite config */ if (config) { g_clear_object (&priv->dev_ip4_config); priv->dev_ip4_config = g_object_ref (config); } composite = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); ensure_con_ipx_config (self); if (priv->dev_ip4_config) nm_ip4_config_merge (composite, priv->dev_ip4_config); if (priv->vpn4_config) nm_ip4_config_merge (composite, priv->vpn4_config); if (priv->ext_ip4_config) nm_ip4_config_merge (composite, priv->ext_ip4_config); /* Merge WWAN config *last* to ensure modem-given settings overwrite * any external stuff set by pppd or other scripts. */ if (priv->wwan_ip4_config) nm_ip4_config_merge (composite, priv->wwan_ip4_config); /* Merge user overrides into the composite config. For assumed connection, * con_ip4_config is empty. */ if (priv->con_ip4_config) nm_ip4_config_merge (composite, priv->con_ip4_config); connection = nm_device_get_connection (self); /* Add the default route. * * We keep track of the default route of a device in a private field. * NMDevice needs to know the default route at this point, because the gateway * might require a direct route (see below). * * But also, we don't want to add the default route to priv->ip4_config, * because the default route from the setting might not be the same that * NMDefaultRouteManager eventually configures (because the it might * tweak the effective metric). */ /* unless we come to a different conclusion below, we have no default route and * the route is assumed. */ priv->default_route.v4_has = FALSE; priv->default_route.v4_is_assumed = TRUE; if (!commit) { /* during a non-commit event, we always pickup whatever is configured. */ goto END_ADD_DEFAULT_ROUTE; } if (nm_device_uses_assumed_connection (self)) goto END_ADD_DEFAULT_ROUTE; /* we are about to commit (for a non-assumed connection). Enforce whatever we have * configured. */ priv->default_route.v4_is_assumed = FALSE; if ( !connection || !nm_default_route_manager_ip4_connection_has_default_route (nm_default_route_manager_get (), connection)) goto END_ADD_DEFAULT_ROUTE; if (!nm_ip4_config_get_num_addresses (composite)) { /* without addresses we can have no default route. */ goto END_ADD_DEFAULT_ROUTE; } gateway = nm_ip4_config_get_gateway (composite); if ( !gateway && nm_device_get_device_type (self) != NM_DEVICE_TYPE_MODEM) goto END_ADD_DEFAULT_ROUTE; has_direct_route = ( gateway == 0 || nm_ip4_config_get_subnet_for_host (composite, gateway) || nm_ip4_config_get_direct_route_for_host (composite, gateway)); priv->default_route.v4_has = TRUE; memset (&priv->default_route.v4, 0, sizeof (priv->default_route.v4)); priv->default_route.v4.source = NM_IP_CONFIG_SOURCE_USER; priv->default_route.v4.gateway = gateway; priv->default_route.v4.metric = default_route_metric; priv->default_route.v4.mss = nm_ip4_config_get_mss (composite); if (!has_direct_route) { NMPlatformIP4Route r = priv->default_route.v4; /* add a direct route to the gateway */ r.network = gateway; r.plen = 32; r.gateway = 0; nm_ip4_config_add_route (composite, &r); } END_ADD_DEFAULT_ROUTE: if (priv->default_route.v4_is_assumed) { /* If above does not explicitly assign a default route, we always pick up the * default route based on what is currently configured. * That means that even managed connections with never-default, can * get a default route (if configured externally). */ priv->default_route.v4_has = _device_get_default_route_from_platform (self, AF_INET, (NMPlatformIPRoute *) &priv->default_route.v4); } /* Allow setting MTU etc */ if (commit) { if (NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit) NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit (self, composite); } success = nm_device_set_ip4_config (self, composite, default_route_metric, commit, out_reason); g_object_unref (composite); return success; } static void dhcp4_lease_change (NMDevice *self, NMIP4Config *config) { NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; g_return_if_fail (config != NULL); if (!ip4_config_merge_and_apply (self, config, TRUE, &reason)) { _LOGW (LOGD_DHCP4, "failed to update IPv4 config for DHCP change."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } else { /* Notify dispatcher scripts of new DHCP4 config */ nm_dispatcher_call (DISPATCHER_ACTION_DHCP4_CHANGE, nm_device_get_connection (self), self, NULL, NULL, NULL); } } static void dhcp4_fail (NMDevice *self, gboolean timeout) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); dhcp4_cleanup (self, TRUE, FALSE); if (timeout || (priv->ip4_state == IP_CONF)) nm_device_activate_schedule_ip4_config_timeout (self); else if (priv->ip4_state == IP_DONE) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); else g_warn_if_reached (); } static void dhcp4_update_config (NMDevice *self, NMDhcp4Config *config, GHashTable *options) { GHashTableIter iter; const char *key, *value; /* Update the DHCP4 config object with new DHCP options */ nm_dhcp4_config_reset (config); g_hash_table_iter_init (&iter, options); while (g_hash_table_iter_next (&iter, (gpointer) &key, (gpointer) &value)) nm_dhcp4_config_add_option (config, key, value); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP4_CONFIG); } static void dhcp4_state_changed (NMDhcpClient *client, NMDhcpState state, NMIP4Config *ip4_config, GHashTable *options, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == FALSE); g_return_if_fail (!ip4_config || NM_IS_IP4_CONFIG (ip4_config)); _LOGD (LOGD_DHCP4, "new DHCPv4 client state %d", state); switch (state) { case NM_DHCP_STATE_BOUND: if (!ip4_config) { _LOGW (LOGD_DHCP4, "failed to get IPv4 config in response to DHCP event."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE); break; } dhcp4_update_config (self, priv->dhcp4_config, options); if (priv->ip4_state == IP_CONF) nm_device_activate_schedule_ip4_config_result (self, ip4_config); else if (priv->ip4_state == IP_DONE) dhcp4_lease_change (self, ip4_config); break; case NM_DHCP_STATE_TIMEOUT: dhcp4_fail (self, TRUE); break; case NM_DHCP_STATE_EXPIRE: /* Ignore expiry before we even have a lease (NAK, old lease, etc) */ if (priv->ip4_state == IP_CONF) break; /* Fall through */ case NM_DHCP_STATE_DONE: case NM_DHCP_STATE_FAIL: dhcp4_fail (self, FALSE); break; default: break; } } static NMActStageReturn dhcp4_start (NMDevice *self, NMConnection *connection, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMSettingIPConfig *s_ip4; const guint8 *hw_addr; size_t hw_addr_len = 0; GByteArray *tmp = NULL; s_ip4 = nm_connection_get_setting_ip4_config (connection); /* Clear old exported DHCP options */ if (priv->dhcp4_config) g_object_unref (priv->dhcp4_config); priv->dhcp4_config = nm_dhcp4_config_new (); hw_addr = nm_platform_link_get_address (nm_device_get_ip_ifindex (self), &hw_addr_len); if (hw_addr_len) { tmp = g_byte_array_sized_new (hw_addr_len); g_byte_array_append (tmp, hw_addr, hw_addr_len); } /* Begin DHCP on the interface */ g_warn_if_fail (priv->dhcp4_client == NULL); priv->dhcp4_client = nm_dhcp_manager_start_ip4 (nm_dhcp_manager_get (), nm_device_get_ip_iface (self), nm_device_get_ip_ifindex (self), tmp, nm_connection_get_uuid (connection), nm_device_get_ip4_route_metric (self), nm_setting_ip_config_get_dhcp_send_hostname (s_ip4), nm_setting_ip_config_get_dhcp_hostname (s_ip4), nm_setting_ip4_config_get_dhcp_client_id (NM_SETTING_IP4_CONFIG (s_ip4)), priv->dhcp_timeout, priv->dhcp_anycast_address, NULL); if (tmp) g_byte_array_free (tmp, TRUE); if (!priv->dhcp4_client) { *reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED; return NM_ACT_STAGE_RETURN_FAILURE; } priv->dhcp4_state_sigid = g_signal_connect (priv->dhcp4_client, NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED, G_CALLBACK (dhcp4_state_changed), self); nm_device_add_pending_action (self, PENDING_ACTION_DHCP4, TRUE); /* DHCP devices will be notified by the DHCP manager when stuff happens */ return NM_ACT_STAGE_RETURN_POSTPONE; } gboolean nm_device_dhcp4_renew (NMDevice *self, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMActStageReturn ret; NMDeviceStateReason reason; NMConnection *connection; g_return_val_if_fail (priv->dhcp4_client != NULL, FALSE); _LOGI (LOGD_DHCP4, "DHCPv4 lease renewal requested"); /* Terminate old DHCP instance and release the old lease */ dhcp4_cleanup (self, TRUE, release); connection = nm_device_get_connection (self); g_assert (connection); /* Start DHCP again on the interface */ ret = dhcp4_start (self, connection, &reason); return (ret != NM_ACT_STAGE_RETURN_FAILURE); } /*********************************************/ static GHashTable *shared_ips = NULL; static void release_shared_ip (gpointer data) { g_hash_table_remove (shared_ips, data); } static gboolean reserve_shared_ip (NMDevice *self, NMSettingIPConfig *s_ip4, NMPlatformIP4Address *address) { if (G_UNLIKELY (shared_ips == NULL)) shared_ips = g_hash_table_new (g_direct_hash, g_direct_equal); memset (address, 0, sizeof (*address)); if (s_ip4 && nm_setting_ip_config_get_num_addresses (s_ip4)) { /* Use the first user-supplied address */ NMIPAddress *user = nm_setting_ip_config_get_address (s_ip4, 0); g_assert (user); nm_ip_address_get_address_binary (user, &address->address); address->plen = nm_ip_address_get_prefix (user); } else { /* Find an unused address in the 10.42.x.x range */ guint32 start = (guint32) ntohl (0x0a2a0001); /* 10.42.0.1 */ guint32 count = 0; while (g_hash_table_lookup (shared_ips, GUINT_TO_POINTER (start + count))) { count += ntohl (0x100); if (count > ntohl (0xFE00)) { _LOGE (LOGD_SHARING, "ran out of shared IP addresses!"); return FALSE; } } address->address = start + count; address->plen = 24; g_hash_table_insert (shared_ips, GUINT_TO_POINTER (address->address), GUINT_TO_POINTER (TRUE)); } return TRUE; } static NMIP4Config * shared4_new_config (NMDevice *self, NMConnection *connection, NMDeviceStateReason *reason) { NMIP4Config *config = NULL; NMPlatformIP4Address address; g_return_val_if_fail (self != NULL, NULL); if (!reserve_shared_ip (self, nm_connection_get_setting_ip4_config (connection), &address)) { *reason = NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE; return NULL; } config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); address.source = NM_IP_CONFIG_SOURCE_SHARED; nm_ip4_config_add_address (config, &address); /* Remove the address lock when the object gets disposed */ g_object_set_data_full (G_OBJECT (config), "shared-ip", GUINT_TO_POINTER (address.address), release_shared_ip); return config; } /*********************************************/ static gboolean connection_ip4_method_requires_carrier (NMConnection *connection, gboolean *out_ip4_enabled) { const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); static const char *ip4_carrier_methods[] = { NM_SETTING_IP4_CONFIG_METHOD_AUTO, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL, NULL }; if (out_ip4_enabled) *out_ip4_enabled = !!strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED); return _nm_utils_string_in_list (method, ip4_carrier_methods); } static gboolean connection_ip6_method_requires_carrier (NMConnection *connection, gboolean *out_ip6_enabled) { const char *method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); static const char *ip6_carrier_methods[] = { NM_SETTING_IP6_CONFIG_METHOD_AUTO, NM_SETTING_IP6_CONFIG_METHOD_DHCP, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL, NULL }; if (out_ip6_enabled) *out_ip6_enabled = !!strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE); return _nm_utils_string_in_list (method, ip6_carrier_methods); } static gboolean connection_requires_carrier (NMConnection *connection) { NMSettingIPConfig *s_ip4, *s_ip6; gboolean ip4_carrier_wanted, ip6_carrier_wanted; gboolean ip4_used = FALSE, ip6_used = FALSE; ip4_carrier_wanted = connection_ip4_method_requires_carrier (connection, &ip4_used); if (ip4_carrier_wanted) { /* If IPv4 wants a carrier and cannot fail, the whole connection * requires a carrier regardless of the IPv6 method. */ s_ip4 = nm_connection_get_setting_ip4_config (connection); if (s_ip4 && !nm_setting_ip_config_get_may_fail (s_ip4)) return TRUE; } ip6_carrier_wanted = connection_ip6_method_requires_carrier (connection, &ip6_used); if (ip6_carrier_wanted) { /* If IPv6 wants a carrier and cannot fail, the whole connection * requires a carrier regardless of the IPv4 method. */ s_ip6 = nm_connection_get_setting_ip6_config (connection); if (s_ip6 && !nm_setting_ip_config_get_may_fail (s_ip6)) return TRUE; } /* If an IP version wants a carrier and and the other IP version isn't * used, the connection requires carrier since it will just fail without one. */ if (ip4_carrier_wanted && !ip6_used) return TRUE; if (ip6_carrier_wanted && !ip4_used) return TRUE; /* If both want a carrier, the whole connection wants a carrier */ return ip4_carrier_wanted && ip6_carrier_wanted; } static gboolean have_any_ready_slaves (NMDevice *self, const GSList *slaves) { const GSList *iter; /* Any enslaved slave is "ready" in the generic case as it's * at least >= NM_DEVCIE_STATE_IP_CONFIG and has had Layer 2 * properties set up. */ for (iter = slaves; iter; iter = g_slist_next (iter)) { if (nm_device_get_enslaved (iter->data)) return TRUE; } return FALSE; } static gboolean ip4_requires_slaves (NMConnection *connection) { const char *method; method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); return strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0; } static NMActStageReturn act_stage3_ip4_config_start (NMDevice *self, NMIP4Config **out_config, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE; const char *method; GSList *slaves; gboolean ready_slaves; g_return_val_if_fail (reason != NULL, NM_ACT_STAGE_RETURN_FAILURE); connection = nm_device_get_connection (self); g_assert (connection); if ( connection_ip4_method_requires_carrier (connection, NULL) && priv->is_master && !priv->carrier) { _LOGI (LOGD_IP4 | LOGD_DEVICE, "IPv4 config waiting until carrier is on"); return NM_ACT_STAGE_RETURN_WAIT; } if (priv->is_master && ip4_requires_slaves (connection)) { /* If the master has no ready slaves, and depends on slaves for * a successful IPv4 attempt, then postpone IPv4 addressing. */ slaves = nm_device_master_get_slaves (self); ready_slaves = NM_DEVICE_GET_CLASS (self)->have_any_ready_slaves (self, slaves); g_slist_free (slaves); if (ready_slaves == FALSE) { _LOGI (LOGD_DEVICE | LOGD_IP4, "IPv4 config waiting until slaves are ready"); return NM_ACT_STAGE_RETURN_WAIT; } } method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG); /* Start IPv4 addressing based on the method requested */ if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO) == 0) ret = dhcp4_start (self, connection, reason); else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL) == 0) ret = aipd_start (self, reason); else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_MANUAL) == 0) { /* Use only IPv4 config from the connection data */ *out_config = nm_ip4_config_new (nm_device_get_ip_ifindex (self)); g_assert (*out_config); ret = NM_ACT_STAGE_RETURN_SUCCESS; } else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_SHARED) == 0) { *out_config = shared4_new_config (self, connection, reason); if (*out_config) { priv->dnsmasq_manager = nm_dnsmasq_manager_new (nm_device_get_ip_iface (self)); ret = NM_ACT_STAGE_RETURN_SUCCESS; } else ret = NM_ACT_STAGE_RETURN_FAILURE; } else if (strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED) == 0) { /* Nothing to do... */ ret = NM_ACT_STAGE_RETURN_STOP; } else _LOGW (LOGD_IP4, "unhandled IPv4 config method '%s'; will fail", method); return ret; } /*********************************************/ /* DHCPv6 stuff */ static void dhcp6_cleanup (NMDevice *self, gboolean stop, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); priv->dhcp6_mode = NM_RDISC_DHCP_LEVEL_NONE; g_clear_object (&priv->dhcp6_ip6_config); if (priv->dhcp6_client) { if (priv->dhcp6_state_sigid) { g_signal_handler_disconnect (priv->dhcp6_client, priv->dhcp6_state_sigid); priv->dhcp6_state_sigid = 0; } if (stop) nm_dhcp_client_stop (priv->dhcp6_client, release); g_clear_object (&priv->dhcp6_client); } nm_device_remove_pending_action (self, PENDING_ACTION_DHCP6, FALSE); if (priv->dhcp6_config) { g_clear_object (&priv->dhcp6_config); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP6_CONFIG); } } static gboolean ip6_config_merge_and_apply (NMDevice *self, gboolean commit, NMDeviceStateReason *out_reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; gboolean success; NMIP6Config *composite; gboolean has_direct_route; const struct in6_addr *gateway; /* If no config was passed in, create a new one */ composite = nm_ip6_config_new (nm_device_get_ip_ifindex (self)); ensure_con_ipx_config (self); g_assert (composite); /* Merge all the IP configs into the composite config */ if (priv->ac_ip6_config) nm_ip6_config_merge (composite, priv->ac_ip6_config); if (priv->dhcp6_ip6_config) nm_ip6_config_merge (composite, priv->dhcp6_ip6_config); if (priv->vpn6_config) nm_ip6_config_merge (composite, priv->vpn6_config); if (priv->ext_ip6_config) nm_ip6_config_merge (composite, priv->ext_ip6_config); /* Merge WWAN config *last* to ensure modem-given settings overwrite * any external stuff set by pppd or other scripts. */ if (priv->wwan_ip6_config) nm_ip6_config_merge (composite, priv->wwan_ip6_config); /* Merge user overrides into the composite config. For assumed connections, * con_ip6_config is empty. */ if (priv->con_ip6_config) nm_ip6_config_merge (composite, priv->con_ip6_config); connection = nm_device_get_connection (self); /* Add the default route. * * We keep track of the default route of a device in a private field. * NMDevice needs to know the default route at this point, because the gateway * might require a direct route (see below). * * But also, we don't want to add the default route to priv->ip6_config, * because the default route from the setting might not be the same that * NMDefaultRouteManager eventually configures (because the it might * tweak the effective metric). */ /* unless we come to a different conclusion below, we have no default route and * the route is assumed. */ priv->default_route.v6_has = FALSE; priv->default_route.v6_is_assumed = TRUE; if (!commit) { /* during a non-commit event, we always pickup whatever is configured. */ goto END_ADD_DEFAULT_ROUTE; } if (nm_device_uses_assumed_connection (self)) goto END_ADD_DEFAULT_ROUTE; /* we are about to commit (for a non-assumed connection). Enforce whatever we have * configured. */ priv->default_route.v6_is_assumed = FALSE; if ( !connection || !nm_default_route_manager_ip6_connection_has_default_route (nm_default_route_manager_get (), connection)) goto END_ADD_DEFAULT_ROUTE; if (!nm_ip6_config_get_num_addresses (composite)) { /* without addresses we can have no default route. */ goto END_ADD_DEFAULT_ROUTE; } gateway = nm_ip6_config_get_gateway (composite); if (!gateway) goto END_ADD_DEFAULT_ROUTE; has_direct_route = nm_ip6_config_get_direct_route_for_host (composite, gateway) != NULL; priv->default_route.v6_has = TRUE; memset (&priv->default_route.v6, 0, sizeof (priv->default_route.v6)); priv->default_route.v6.source = NM_IP_CONFIG_SOURCE_USER; priv->default_route.v6.gateway = *gateway; priv->default_route.v6.metric = nm_device_get_ip6_route_metric (self); priv->default_route.v6.mss = nm_ip6_config_get_mss (composite); if (!has_direct_route) { NMPlatformIP6Route r = priv->default_route.v6; /* add a direct route to the gateway */ r.network = *gateway; r.plen = 128; r.gateway = in6addr_any; nm_ip6_config_add_route (composite, &r); } END_ADD_DEFAULT_ROUTE: if (priv->default_route.v6_is_assumed) { /* If above does not explicitly assign a default route, we always pick up the * default route based on what is currently configured. * That means that even managed connections with never-default, can * get a default route (if configured externally). */ priv->default_route.v6_has = _device_get_default_route_from_platform (self, AF_INET6, (NMPlatformIPRoute *) &priv->default_route.v6); } nm_ip6_config_addresses_sort (composite, priv->rdisc ? priv->rdisc_use_tempaddr : NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN); /* Allow setting MTU etc */ if (commit) { if (NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit) NM_DEVICE_GET_CLASS (self)->ip6_config_pre_commit (self, composite); } success = nm_device_set_ip6_config (self, composite, commit, out_reason); g_object_unref (composite); return success; } static void dhcp6_lease_change (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMDeviceStateReason reason = NM_DEVICE_STATE_REASON_NONE; if (priv->dhcp6_ip6_config == NULL) { _LOGW (LOGD_DHCP6, "failed to get DHCPv6 config for rebind"); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); return; } g_assert (priv->dhcp6_client); /* sanity check */ connection = nm_device_get_connection (self); g_assert (connection); /* Apply the updated config */ if (ip6_config_merge_and_apply (self, TRUE, &reason) == FALSE) { _LOGW (LOGD_DHCP6, "failed to update IPv6 config in response to DHCP event."); nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason); } else { /* Notify dispatcher scripts of new DHCPv6 config */ nm_dispatcher_call (DISPATCHER_ACTION_DHCP6_CHANGE, connection, self, NULL, NULL, NULL); } } static void dhcp6_fail (NMDevice *self, gboolean timeout) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); dhcp6_cleanup (self, TRUE, FALSE); if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED) { if (timeout || (priv->ip6_state == IP_CONF)) nm_device_activate_schedule_ip6_config_timeout (self); else if (priv->ip6_state == IP_DONE) nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED); else g_warn_if_reached (); } else { /* not a hard failure; just live with the RA info */ if (priv->ip6_state == IP_CONF) nm_device_activate_schedule_ip6_config_result (self); } } static void dhcp6_timeout (NMDevice *self, NMDhcpClient *client) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_MANAGED) dhcp6_fail (self, TRUE); else { /* not a hard failure; just live with the RA info */ dhcp6_cleanup (self, TRUE, FALSE); if (priv->ip6_state == IP_CONF) nm_device_activate_schedule_ip6_config_result (self); } } static void dhcp6_update_config (NMDevice *self, NMDhcp6Config *config, GHashTable *options) { GHashTableIter iter; const char *key, *value; /* Update the DHCP6 config object with new DHCP options */ nm_dhcp6_config_reset (config); g_hash_table_iter_init (&iter, options); while (g_hash_table_iter_next (&iter, (gpointer) &key, (gpointer) &value)) nm_dhcp6_config_add_option (config, key, value); g_object_notify (G_OBJECT (self), NM_DEVICE_DHCP6_CONFIG); } static void dhcp6_state_changed (NMDhcpClient *client, NMDhcpState state, NMIP6Config *ip6_config, GHashTable *options, gpointer user_data) { NMDevice *self = NM_DEVICE (user_data); NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_if_fail (nm_dhcp_client_get_ipv6 (client) == TRUE); g_return_if_fail (!ip6_config || NM_IS_IP6_CONFIG (ip6_config)); _LOGD (LOGD_DHCP6, "new DHCPv6 client state %d", state); switch (state) { case NM_DHCP_STATE_BOUND: g_clear_object (&priv->dhcp6_ip6_config); if (ip6_config) { priv->dhcp6_ip6_config = g_object_ref (ip6_config); dhcp6_update_config (self, priv->dhcp6_config, options); } if (priv->ip6_state == IP_CONF) { if (priv->dhcp6_ip6_config == NULL) { /* FIXME: Initial DHCP failed; should we fail IPv6 entirely then? */ nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DHCP_FAILED); break; } nm_device_activate_schedule_ip6_config_result (self); } else if (priv->ip6_state == IP_DONE) dhcp6_lease_change (self); break; case NM_DHCP_STATE_TIMEOUT: dhcp6_timeout (self, client); break; case NM_DHCP_STATE_EXPIRE: /* Ignore expiry before we even have a lease (NAK, old lease, etc) */ if (priv->ip6_state != IP_CONF) dhcp6_fail (self, FALSE); break; case NM_DHCP_STATE_DONE: /* In IPv6 info-only mode, the client doesn't handle leases so it * may exit right after getting a response from the server. That's * normal. In that case we just ignore the exit. */ if (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF) break; /* Otherwise, fall through */ case NM_DHCP_STATE_FAIL: dhcp6_fail (self, FALSE); break; default: break; } } static gboolean dhcp6_start_with_link_ready (NMDevice *self, NMConnection *connection) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMSettingIPConfig *s_ip6; GByteArray *tmp = NULL; const guint8 *hw_addr; size_t hw_addr_len = 0; g_assert (connection); s_ip6 = nm_connection_get_setting_ip6_config (connection); g_assert (s_ip6); hw_addr = nm_platform_link_get_address (nm_device_get_ip_ifindex (self), &hw_addr_len); if (hw_addr_len) { tmp = g_byte_array_sized_new (hw_addr_len); g_byte_array_append (tmp, hw_addr, hw_addr_len); } priv->dhcp6_client = nm_dhcp_manager_start_ip6 (nm_dhcp_manager_get (), nm_device_get_ip_iface (self), nm_device_get_ip_ifindex (self), tmp, nm_connection_get_uuid (connection), nm_device_get_ip6_route_metric (self), nm_setting_ip_config_get_dhcp_send_hostname (s_ip6), nm_setting_ip_config_get_dhcp_hostname (s_ip6), priv->dhcp_timeout, priv->dhcp_anycast_address, (priv->dhcp6_mode == NM_RDISC_DHCP_LEVEL_OTHERCONF) ? TRUE : FALSE, nm_setting_ip6_config_get_ip6_privacy (NM_SETTING_IP6_CONFIG (s_ip6))); if (tmp) g_byte_array_free (tmp, TRUE); if (priv->dhcp6_client) { priv->dhcp6_state_sigid = g_signal_connect (priv->dhcp6_client, NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED, G_CALLBACK (dhcp6_state_changed), self); } return !!priv->dhcp6_client; } static gboolean dhcp6_start (NMDevice *self, gboolean wait_for_ll, NMDeviceStateReason *reason) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; NMSettingIPConfig *s_ip6; g_clear_object (&priv->dhcp6_config); priv->dhcp6_config = nm_dhcp6_config_new (); g_warn_if_fail (priv->dhcp6_ip6_config == NULL); g_clear_object (&priv->dhcp6_ip6_config); connection = nm_device_get_connection (self); g_assert (connection); s_ip6 = nm_connection_get_setting_ip6_config (connection); if (!nm_setting_ip_config_get_may_fail (s_ip6) || !strcmp (nm_setting_ip_config_get_method (s_ip6), NM_SETTING_IP6_CONFIG_METHOD_DHCP)) nm_device_add_pending_action (self, PENDING_ACTION_DHCP6, TRUE); if (wait_for_ll) { NMActStageReturn ret; /* ensure link local is ready... */ ret = linklocal6_start (self); if (ret == NM_ACT_STAGE_RETURN_POSTPONE) { /* success; wait for the LL address to show up */ return TRUE; } /* success; already have the LL address; kick off DHCP */ g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS); } if (!dhcp6_start_with_link_ready (self, connection)) { *reason = NM_DEVICE_STATE_REASON_DHCP_START_FAILED; return FALSE; } return TRUE; } gboolean nm_device_dhcp6_renew (NMDevice *self, gboolean release) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); g_return_val_if_fail (priv->dhcp6_client != NULL, FALSE); _LOGI (LOGD_DHCP6, "DHCPv6 lease renewal requested"); /* Terminate old DHCP instance and release the old lease */ dhcp6_cleanup (self, TRUE, release); /* Start DHCP again on the interface */ return dhcp6_start (self, FALSE, NULL); } /******************************************/ static gboolean have_ip6_address (const NMIP6Config *ip6_config, gboolean linklocal) { guint i; if (!ip6_config) return FALSE; linklocal = !!linklocal; for (i = 0; i < nm_ip6_config_get_num_addresses (ip6_config); i++) { const NMPlatformIP6Address *addr = nm_ip6_config_get_address (ip6_config, i); if ((IN6_IS_ADDR_LINKLOCAL (&addr->address) == linklocal) && !(addr->flags & IFA_F_TENTATIVE)) return TRUE; } return FALSE; } static void linklocal6_cleanup (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); if (priv->linklocal6_timeout_id) { g_source_remove (priv->linklocal6_timeout_id); priv->linklocal6_timeout_id = 0; } } static gboolean linklocal6_timeout_cb (gpointer user_data) { NMDevice *self = user_data; linklocal6_cleanup (self); _LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses failed due to timeout"); nm_device_activate_schedule_ip6_config_timeout (self); return G_SOURCE_REMOVE; } static void linklocal6_complete (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; g_assert (priv->linklocal6_timeout_id); g_assert (have_ip6_address (priv->ip6_config, TRUE)); linklocal6_cleanup (self); connection = nm_device_get_connection (self); g_assert (connection); method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); _LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses successful, continue with method %s", method); if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO) == 0) { if (!addrconf6_start_with_link_ready (self)) { /* Time out IPv6 instead of failing the entire activation */ nm_device_activate_schedule_ip6_config_timeout (self); } } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_DHCP) == 0) { if (!dhcp6_start_with_link_ready (self, connection)) { /* Time out IPv6 instead of failing the entire activation */ nm_device_activate_schedule_ip6_config_timeout (self); } } else if (strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL) == 0) nm_device_activate_schedule_ip6_config_result (self); else g_return_if_fail (FALSE); } static void check_and_add_ipv6ll_addr (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); int ip_ifindex = nm_device_get_ip_ifindex (self); NMUtilsIPv6IfaceId iid; struct in6_addr lladdr; guint i, n; if (priv->nm_ipv6ll == FALSE) return; if (priv->ip6_config) { n = nm_ip6_config_get_num_addresses (priv->ip6_config); for (i = 0; i < n; i++) { const NMPlatformIP6Address *addr; addr = nm_ip6_config_get_address (priv->ip6_config, i); if (IN6_IS_ADDR_LINKLOCAL (&addr->address)) { /* Already have an LL address, nothing to do */ return; } } } if (!nm_device_get_ip_iface_identifier (self, &iid)) { _LOGW (LOGD_IP6, "failed to get interface identifier; IPv6 may be broken"); return; } memset (&lladdr, 0, sizeof (lladdr)); lladdr.s6_addr16[0] = htons (0xfe80); nm_utils_ipv6_addr_set_interface_identfier (&lladdr, iid); _LOGD (LOGD_IP6, "adding IPv6LL address %s", nm_utils_inet6_ntop (&lladdr, NULL)); if (!nm_platform_ip6_address_add (ip_ifindex, lladdr, in6addr_any, 64, NM_PLATFORM_LIFETIME_PERMANENT, NM_PLATFORM_LIFETIME_PERMANENT, 0)) { _LOGW (LOGD_IP6, "failed to add IPv6 link-local address %s", nm_utils_inet6_ntop (&lladdr, NULL)); } } static NMActStageReturn linklocal6_start (NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); NMConnection *connection; const char *method; linklocal6_cleanup (self); if (have_ip6_address (priv->ip6_config, TRUE)) return NM_ACT_STAGE_RETURN_SUCCESS; connection = nm_device_get_connection (self); g_assert (connection); method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG); _LOGD (LOGD_DEVICE, "linklocal6: starting IPv6 with method '%s', but the device has no link-local addresses configured. Wait.", method); check_and_add_ipv6ll_addr (self); priv->linklocal6_timeout_id = g_timeout_add_seconds (5, linklocal6_timeout_cb, self); return NM_ACT_STAGE_RETURN_POSTPONE; } /******************************************/ static void print_support_extended_ifa_flags (NMSettingIP6ConfigPrivacy use_tempaddr) { static gint8 warn = 0; static gint8 s_libnl = -1, s_kernel; if (warn >= 2) return; if (s_libnl == -1) { s_libnl = !!nm_platform_check_support_libnl_extended_ifa_flags (); s_kernel = !!nm_platform_check_support_kernel_extended_ifa_flags (); if (s_libnl && s_kernel) { nm_log_dbg (LOGD_IP6, "kernel and libnl support extended IFA_FLAGS (needed by NM for IPv6 private addresses)"); warn = 2; return; } } if ( use_tempaddr != NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR && use_tempaddr != NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR) { if (warn == 0) { nm_log_dbg (LOGD_IP6, "%s%s%s %s not support extended IFA_FLAGS (needed by NM for IPv6 private addresses)", !s_kernel ? "kernel" : "", !s_kernel && !s_libnl ? " and " : "", !s_libnl ? "libnl" : "", !s_kernel && !s_libnl ? "do" : "does"); warn = 1; } return; } if (!s_libnl && !s_kernel) { nm_log_warn (LOGD_IP6, "libnl and the kernel do not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } else if (!s_libnl) { nm_log_warn (LOGD_IP6, "libnl does not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } else if (!s_kernel) { nm_log_warn (LOGD_IP6, "The kernel does not support extended IFA_FLAGS needed by NM for " "IPv6 private addresses. This feature is not available"); } warn = 2; } static void rdisc_config_changed (NMRDisc *rdisc, NMRDiscConfigMap changed, NMDevice *self) { NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self); warn = 2; } static void rdisc_config_changed (NMRDisc *rdisc, NMRDiscConfigMap changed, NMDevice *self) { address.preferred = discovered_address->preferred; if (address.preferred > address.lifetime) address.preferred = address.lifetime; address.source = NM_IP_CONFIG_SOURCE_RDISC; address.flags = ifa_flags; nm_ip6_config_add_address (priv->ac_ip6_config, &address); } }
1
linux
0625b4ba1a5d4703c7fb01c497bd6c156908af00
NOT_APPLICABLE
NOT_APPLICABLE
static int set_data_inl_seg(struct mlx5_ib_qp *qp, const struct ib_send_wr *wr, void *wqe, int *sz) { struct mlx5_wqe_inline_seg *seg; void *qend = qp->sq.qend; void *addr; int inl = 0; int copy; int len; int i; seg = wqe; wqe += sizeof(*seg); for (i = 0; i < wr->num_sge; i++) { addr = (void *)(unsigned long)(wr->sg_list[i].addr); len = wr->sg_list[i].length; inl += len; if (unlikely(inl > qp->max_inline_data)) return -ENOMEM; if (unlikely(wqe + len > qend)) { copy = qend - wqe; memcpy(wqe, addr, copy); addr += copy; len -= copy; wqe = mlx5_get_send_wqe(qp, 0); } memcpy(wqe, addr, len); wqe += len; } seg->byte_count = cpu_to_be32(inl | MLX5_INLINE_SEG); *sz = ALIGN(inl + sizeof(seg->byte_count), 16) / 16; return 0; }
0
busybox
150dc7a2b483b8338a3e185c478b4b23ee884e71
NOT_APPLICABLE
NOT_APPLICABLE
d_to_lfp(double d) { l_fixedpt_t lfp; lfp.int_partl = (uint32_t)d; lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX); lfp.int_partl = htonl(lfp.int_partl); lfp.fractionl = htonl(lfp.fractionl); return lfp; }
0
linux
3a50597de8635cd05133bd12c95681c82fe7b878
NOT_APPLICABLE
NOT_APPLICABLE
long keyctl_instantiate_key_iov(key_serial_t id, const struct iovec __user *_payload_iov, unsigned ioc, key_serial_t ringid) { struct iovec iovstack[UIO_FASTIOV], *iov = iovstack; long ret; if (!_payload_iov || !ioc) goto no_payload; ret = rw_copy_check_uvector(WRITE, _payload_iov, ioc, ARRAY_SIZE(iovstack), iovstack, &iov); if (ret < 0) goto err; if (ret == 0) goto no_payload_free; ret = keyctl_instantiate_key_common(id, iov, ioc, ret, ringid); err: if (iov != iovstack) kfree(iov); return ret; no_payload_free: if (iov != iovstack) kfree(iov); no_payload: return keyctl_instantiate_key_common(id, NULL, 0, 0, ringid); }
0
linux
27ae357fa82be5ab73b2ef8d39dcb8ca2563483a
NOT_APPLICABLE
NOT_APPLICABLE
int vm_brk_flags(unsigned long addr, unsigned long len, unsigned long flags) { struct mm_struct *mm = current->mm; int ret; bool populate; LIST_HEAD(uf); if (down_write_killable(&mm->mmap_sem)) return -EINTR; ret = do_brk_flags(addr, len, flags, &uf); populate = ((mm->def_flags & VM_LOCKED) != 0); up_write(&mm->mmap_sem); userfaultfd_unmap_complete(mm, &uf); if (populate && !ret) mm_populate(addr, len); return ret; }
0
samba
0454b95657846fcecf0f51b6f1194faac02518bd
NOT_APPLICABLE
NOT_APPLICABLE
bool ldb_dn_is_special(struct ldb_dn *dn) { if ( ! dn || dn->invalid) return false; return dn->special; }
0
php-src
760ff841a14160f25348f7969985cb8a2c4da3cc
NOT_APPLICABLE
NOT_APPLICABLE
ZEND_API int ZEND_FASTCALL string_locale_compare_function(zval *op1, zval *op2) /* {{{ */ { zend_string *tmp_str1, *tmp_str2; zend_string *str1 = zval_get_tmp_string(op1, &tmp_str1); zend_string *str2 = zval_get_tmp_string(op2, &tmp_str2); int ret = strcoll(ZSTR_VAL(str1), ZSTR_VAL(str2)); zend_tmp_string_release(tmp_str1); zend_tmp_string_release(tmp_str2); return ret; }
0
radare2
0a557045476a2969c7079aec9eeb29d02f2809c6
NOT_APPLICABLE
NOT_APPLICABLE
static void __free_resource(void *resource) { r_ne_resource *res = (r_ne_resource *)resource; free (res->name); r_list_free (res->entry); free (res); }
0
OpenJK
b248763e4878ef12d5835ece6600be8334f67da1
NOT_APPLICABLE
NOT_APPLICABLE
static sfxHandle_t S_AL_BufferFind(const char *filename) { sfxHandle_t sfx = -1; int i; if ( !filename ) { filename = "*default*"; } if ( !filename[0] ) { filename = "*default*"; } if ( strlen( filename ) >= MAX_QPATH ) { Com_Printf( S_COLOR_YELLOW "WARNING: Sound name is too long: %s\n", filename ); return 0; } for(i = 0; i < numSfx; i++) { if(!Q_stricmp(knownSfx[i].filename, filename)) { sfx = i; break; } } if(sfx == -1) { alSfx_t *ptr; sfx = S_AL_BufferFindFree(); ptr = &knownSfx[sfx]; memset(ptr, 0, sizeof(*ptr)); ptr->masterLoopSrc = -1; strcpy(ptr->filename, filename); } return sfx; }
0
Chrome
5385c44d9634d00b1cec2abf0fe7290d4205c7b0
NOT_APPLICABLE
NOT_APPLICABLE
void ResourceDispatcherHostImpl::CancelRequest(int child_id, int request_id, bool from_renderer) { GlobalRequestID id(child_id, request_id); if (from_renderer) { if (transferred_navigations_.find(id) != transferred_navigations_.end()) return; } PendingRequestList::iterator i = pending_requests_.find(id); if (i == pending_requests_.end()) { DVLOG(1) << "Canceling a request that wasn't found"; return; } net::URLRequest* request = i->second; bool started_before_cancel = request->is_pending(); if (CancelRequestInternal(request, from_renderer) && !started_before_cancel) { MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&ResourceDispatcherHostImpl::CallResponseCompleted, base::Unretained(this), child_id, request_id)); } }
0
exempi
baa4b8a02c1ffab9645d13f0bfb1c0d10d311a0c
CVE-2018-7729
CWE-125
void PostScript_MetaHandler::ParsePSFile() { bool found = false; IOBuffer ioBuf; XMP_IO* fileRef = this->parent->ioRef; XMP_AbortProc abortProc = this->parent->abortProc; void * abortArg = this->parent->abortArg; const bool checkAbort = (abortProc != 0); if ( ! PostScript_Support::IsValidPSFile(fileRef,this->fileformat) ) return ; fileRef->Rewind(); if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ; XMP_Uns32 fileheader = GetUns32BE ( ioBuf.ptr ); if ( fileheader == 0xC5D0D3C6 ) { if ( ! CheckFileSpace ( fileRef, &ioBuf, 30 ) ) return ; XMP_Uns32 psOffset = GetUns32LE ( ioBuf.ptr+4 ); // PostScript offset. XMP_Uns32 psLength = GetUns32LE ( ioBuf.ptr+8 ); // PostScript length. setTokenInfo(kPS_EndPostScript,psOffset+psLength,0); MoveToOffset ( fileRef, psOffset, &ioBuf ); } while ( true ) { if ( checkAbort && abortProc(abortArg) ) { XMP_Throw ( "PostScript_MetaHandler::FindPostScriptHint - User abort", kXMPErr_UserAbort ); } if ( ! CheckFileSpace ( fileRef, &ioBuf, kPSContainsForString.length() ) ) return ; if ( (CheckFileSpace ( fileRef, &ioBuf, kPSEndCommentString.length() )&& CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSEndCommentString.c_str()), kPSEndCommentString.length() ) )|| *ioBuf.ptr!='%' || !(*(ioBuf.ptr+1)>32 && *(ioBuf.ptr+1)<=126 )) // implicit endcomment check { if (CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSEndCommentString.c_str()), kPSEndCommentString.length() )) { setTokenInfo(kPS_EndComments,ioBuf.filePos+ioBuf.ptr-ioBuf.data,kPSEndCommentString.length()); ioBuf.ptr+=kPSEndCommentString.length(); } else { setTokenInfo(kPS_EndComments,ioBuf.filePos+ioBuf.ptr-ioBuf.data,0); } while(true) { if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ; if (! IsWhitespace (*ioBuf.ptr)) break; ++ioBuf.ptr; } while(true) { if ( ! CheckFileSpace ( fileRef, &ioBuf, 5 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("/DOCI"), 5 ) && CheckFileSpace ( fileRef, &ioBuf, kPSContainsDocInfoString.length() ) &&CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsDocInfoString.c_str()), kPSContainsDocInfoString.length() )) { ioBuf.ptr+=kPSContainsDocInfoString.length(); ExtractDocInfoDict(ioBuf); }// DOCINFO Not found in document else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Beg"), 5 )) {//possibly one of %%BeginProlog %%BeginSetup %%BeginBinary %%BeginData XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data; ioBuf.ptr+=5; if (!CheckFileSpace ( fileRef, &ioBuf, 6 )) return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("inProl"), 6 )) {//%%BeginProlog ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 2 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("og"), 2 )) { ioBuf.ptr+=2; setTokenInfo(kPS_BeginProlog,begStartpos,13); } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inSetu"), 6 )) {//%%BeginSetup ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 1 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("p"), 1 )) { ioBuf.ptr+=1; setTokenInfo(kPS_BeginSetup,begStartpos,12); } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inBina"), 6 )) {//%%BeginBinary ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 3 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("ry"), 3 )) { ioBuf.ptr+=3; while(true) { if (!CheckFileSpace ( fileRef, &ioBuf, 12 ))return; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndBinary"), 11 )) { ioBuf.ptr+=11; if (IsWhitespace(*ioBuf.ptr)) { ioBuf.ptr++; break; } } ++ioBuf.ptr; } } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inData"), 6 )) {//%%BeginData ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 1 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr(":"), 1 )) { while(true) { if (!CheckFileSpace ( fileRef, &ioBuf, 10 ))return; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndData"), 9 )) { ioBuf.ptr+=9; if (IsWhitespace(*ioBuf.ptr)) { ioBuf.ptr++; break; } } ++ioBuf.ptr; } } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inDocu"), 6 )) {// %%BeginDocument ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 5 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("ment:"), 5 )) { ioBuf.ptr+=5; while(true) { if (!CheckFileSpace ( fileRef, &ioBuf, 14 ))return; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("%%EndDocument"), 13 )) { ioBuf.ptr+=13; if (IsWhitespace(*ioBuf.ptr)) { ioBuf.ptr++; break; } } ++ioBuf.ptr; } } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("inPage"), 6 )) {// %%BeginPageSetup ioBuf.ptr+=6; if (!CheckFileSpace ( fileRef, &ioBuf, 5 ))return; if(CheckBytes ( ioBuf.ptr, Uns8Ptr("Setup"), 5 )) { ioBuf.ptr+=5; setTokenInfo(kPS_BeginPageSetup,begStartpos,16); } } } else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%End"), 5 )) {//possibly %%EndProlog %%EndSetup %%EndPageSetup %%EndPageComments XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data; ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 5 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("Prolo"), 5 )) {// %%EndProlog ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("g"), 1 )) { ioBuf.ptr+=1; setTokenInfo(kPS_EndProlog,begStartpos,11); } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("Setup"), 5 )) {//%%EndSetup ioBuf.ptr+=5; setTokenInfo(kPS_EndSetup,begStartpos,10); } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("PageS"), 5 )) {//%%EndPageSetup ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("etup"), 4 )) { ioBuf.ptr+=4; setTokenInfo(kPS_EndPageSetup,begStartpos,14); } } else if (CheckBytes ( ioBuf.ptr, Uns8Ptr("PageC"), 5 )) {//%%EndPageComments ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 7 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("omments"), 7 )) { ioBuf.ptr+=7; setTokenInfo(kPS_EndPageComments,begStartpos,17); } } } else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Pag"), 5 )) { XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data; ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 2 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr(":"), 2 )) { ioBuf.ptr+=2; while(!IsNewline(*ioBuf.ptr)) { if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ; ++ioBuf.ptr; } setTokenInfo(kPS_Page,begStartpos,ioBuf.filePos+ioBuf.ptr-ioBuf.data-begStartpos); } } else if(CheckBytes ( ioBuf.ptr, Uns8Ptr("%%Tra"), 5 )) { XMP_Int64 begStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data; ioBuf.ptr+=5; if ( ! CheckFileSpace ( fileRef, &ioBuf, 4 ) ) return ; if (CheckBytes ( ioBuf.ptr, Uns8Ptr("iler"), 4 )) { ioBuf.ptr+=4; while(!IsNewline(*ioBuf.ptr)) ++ioBuf.ptr; setTokenInfo(kPS_Trailer,begStartpos,ioBuf.filePos+ioBuf.ptr-ioBuf.data-begStartpos); } } ioBuf.ptr+=5; setTokenInfo(kPS_EOF,ioBuf.filePos+ioBuf.ptr-ioBuf.data,5); } if ( ! CheckFileSpace ( fileRef, &ioBuf, 1 ) ) return ; ++ioBuf.ptr; } return; }else if (!(kPS_Creator & dscFlags) && CheckFileSpace ( fileRef, &ioBuf, kPSContainsForString.length() )&& CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsForString.c_str()), kPSContainsForString.length() )) { ioBuf.ptr+=kPSContainsForString.length(); if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscFor) ) return ; } else if (!(kPS_CreatorTool & dscFlags) && CheckFileSpace ( fileRef, &ioBuf, kPSContainsCreatorString.length() )&& CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsCreatorString.c_str()), kPSContainsCreatorString.length() )) { ioBuf.ptr+=kPSContainsCreatorString.length(); if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscCreator) ) return ; } else if (!(kPS_CreateDate & dscFlags) && CheckFileSpace ( fileRef, &ioBuf, kPSContainsCreateDateString.length() )&& CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsCreateDateString.c_str()), kPSContainsCreateDateString.length() )) { ioBuf.ptr+=kPSContainsCreateDateString.length(); if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscCreateDate) ) return ; } else if (!(kPS_Title & dscFlags) && CheckFileSpace ( fileRef, &ioBuf, kPSContainsTitleString.length() )&& CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsTitleString.c_str()), kPSContainsTitleString.length() )) { ioBuf.ptr+=kPSContainsTitleString.length(); if ( ! ExtractDSCCommentValue(ioBuf,kPS_dscTitle) ) return ; } else if( CheckFileSpace ( fileRef, &ioBuf, kPSContainsXMPString.length() )&& ( CheckBytes ( ioBuf.ptr, Uns8Ptr(kPSContainsXMPString.c_str()), kPSContainsXMPString.length() ) )) { XMP_Int64 containsXMPStartpos=ioBuf.filePos+ioBuf.ptr-ioBuf.data; ioBuf.ptr += kPSContainsXMPString.length(); ExtractContainsXMPHint(ioBuf,containsXMPStartpos); } // Found "%ADO_ContainsXMP:". if ( ! PostScript_Support::SkipUntilNewline(fileRef,ioBuf) ) return ; } // Outer marker loop.
1
Chrome
da9a32b9e282c1653bb6b5c1b8c89a1970905f21
NOT_APPLICABLE
NOT_APPLICABLE
SiteInstance* RenderFrameHostImpl::GetSiteInstance() { return render_view_host_->GetSiteInstance(); }
0
Chrome
f7b020b3d36def118881daa4402c44ca72271482
NOT_APPLICABLE
NOT_APPLICABLE
static AtomicString makeVisibleEmptyValue(const Vector<String>& symbols) { unsigned maximumLength = 0; for (unsigned index = 0; index < symbols.size(); ++index) maximumLength = std::max(maximumLength, numGraphemeClusters(symbols[index])); StringBuilder builder; builder.reserveCapacity(maximumLength); for (unsigned length = 0; length < maximumLength; ++length) builder.append('-'); return builder.toAtomicString(); }
0
Chrome
41f5b55ab27da6890af96f2f8f0f6dd5bc6cc93c
NOT_APPLICABLE
NOT_APPLICABLE
unsigned SkiaOutputSurfaceImpl::UpdateGpuFence() { return 0; }
0
linux
999653786df6954a31044528ac3f7a5dadca08f4
NOT_APPLICABLE
NOT_APPLICABLE
int nfs4_acl_bytes(int entries) { return sizeof(struct nfs4_acl) + entries * sizeof(struct nfs4_ace); }
0
unbound
02080f6b180232f43b77f403d0c038e9360a460f
NOT_APPLICABLE
NOT_APPLICABLE
dnsc_shared_secrets_delkeyfunc(void *k, void* ATTR_UNUSED(arg)) { struct shared_secret_cache_key* ssk = (struct shared_secret_cache_key*)k; lock_rw_destroy(&ssk->entry.lock); free(ssk); }
0
linux
29d6455178a09e1dc340380c582b13356227e8df
NOT_APPLICABLE
NOT_APPLICABLE
unsigned long nr_running(void) { unsigned long i, sum = 0; for_each_online_cpu(i) sum += cpu_rq(i)->nr_running; return sum; }
0
qemu
eb7a20a3616085d46aa6b4b4224e15587ec67e6e
NOT_APPLICABLE
NOT_APPLICABLE
static uint32_t i6300esb_mem_readw(void *vp, hwaddr addr) { uint32_t data = 0; I6300State *d = vp; i6300esb_debug("addr = %x\n", (int) addr); if (addr == 0xc) { /* The previous reboot flag is really bit 9, but there is * a bug in the Linux driver where it thinks it's bit 12. * Set both. */ data = d->previous_reboot_flag ? 0x1200 : 0; } return data; }
0
tensorflow
4d74d8a00b07441cba090a02e0dd9ed385145bf4
NOT_APPLICABLE
NOT_APPLICABLE
void Compute(OpKernelContext* context) override { const Tensor& logits_in = context->input(0); const Tensor& labels_in = context->input(1); TensorShape shape_in = logits_in.shape(); BCast bcast(BCast::FromShape(logits_in.shape()), BCast::FromShape(labels_in.shape()), /*fewer_dims_optimization=*/false); if (!logits_in.IsSameSize(labels_in)) { OP_REQUIRES(context, bcast.IsValid(), errors::InvalidArgument( "logits and labels must be broadcastable: logits_size=", logits_in.shape().DebugString(), " labels_size=", labels_in.shape().DebugString())); shape_in = BCast::ToShape(bcast.output_shape()); } OP_REQUIRES(context, TensorShapeUtils::IsMatrix(shape_in), errors::InvalidArgument("logits and labels must be either " "2-dimensional, or broadcasted to be " "2-dimensional")); if (std::is_same<Device, GPUDevice>::value) { OP_REQUIRES(context, !OpDeterminismRequired(), errors::Unimplemented( "The GPU implementation of SoftmaxCrossEntropyWithLogits" " that would have been executed is not deterministic." " Note that the Python API uses an alternative," " deterministic, GPU-accelerated path when determinism is" " enabled.")); } // loss is 1-D (one per example), and size is batch_size. Tensor scratch; OP_REQUIRES_OK( context, context->allocate_temp(DataTypeToEnum<T>::value, TensorShape({shape_in.dim_size(0), 1}), &scratch)); Tensor* loss_out = nullptr; OP_REQUIRES_OK(context, context->allocate_output( 0, TensorShape({shape_in.dim_size(0)}), &loss_out)); Tensor* back_out = nullptr; // Try to reuse the logits_in buffer for the backprop output. OP_REQUIRES_OK(context, context->forward_input_or_allocate_output( {0}, 1, shape_in, &back_out)); if (shape_in.dim_size(0) > 0) { functor::XentFunctor<Device, T> functor; functor(context->eigen_device<Device>(), shape_in.AsEigenDSizes<2>(), BCast::ToIndexArray<2>(bcast.x_bcast()), BCast::ToIndexArray<2>(bcast.y_bcast()), logits_in.template shaped<T, 2>(bcast.x_reshape()), labels_in.template shaped<T, 2>(bcast.y_reshape()), scratch.matrix<T>(), loss_out->vec<T>(), back_out->matrix<T>()); } }
0
chrony
7712455d9aa33d0db0945effaa07e900b85987b1
NOT_APPLICABLE
NOT_APPLICABLE
handle_modify_polltarget(CMD_Request *rx_message, CMD_Reply *tx_message) { int status; IPAddr address; UTI_IPNetworkToHost(&rx_message->data.modify_polltarget.address, &address); status = NSR_ModifyPolltarget(&address, ntohl(rx_message->data.modify_polltarget.new_poll_target)); if (status) { tx_message->status = htons(STT_SUCCESS); } else { tx_message->status = htons(STT_NOSUCHSOURCE); } }
0
samba
0998f2f1bced019db4000ef4b55887abcb65f6d2
NOT_APPLICABLE
NOT_APPLICABLE
static int ldb_kv_index_dn_leaf(struct ldb_module *module, struct ldb_kv_private *ldb_kv, const struct ldb_parse_tree *tree, struct dn_list *list) { if (ldb_kv->disallow_dn_filter && (ldb_attr_cmp(tree->u.equality.attr, "dn") == 0)) { /* in AD mode we do not support "(dn=...)" search filters */ list->dn = NULL; list->count = 0; return LDB_SUCCESS; } if (tree->u.equality.attr[0] == '@') { /* Do not allow a indexed search against an @ */ list->dn = NULL; list->count = 0; return LDB_SUCCESS; } if (ldb_attr_dn(tree->u.equality.attr) == 0) { enum key_truncation truncation = KEY_NOT_TRUNCATED; struct ldb_dn *dn = ldb_dn_from_ldb_val(list, ldb_module_get_ctx(module), &tree->u.equality.value); if (dn == NULL) { /* If we can't parse it, no match */ list->dn = NULL; list->count = 0; return LDB_SUCCESS; } /* * Re-use the same code we use for a SCOPE_BASE * search * * We can't call TALLOC_FREE(dn) as this must belong * to list for the memory to remain valid. */ return ldb_kv_index_dn_base_dn( module, ldb_kv, dn, list, &truncation); /* * We ignore truncation here and allow multi-valued matches * as ltdb_search_indexed will filter out the wrong one in * ltdb_index_filter() which calls ldb_match_message(). */ } else if ((ldb_kv->cache->GUID_index_attribute != NULL) && (ldb_attr_cmp(tree->u.equality.attr, ldb_kv->cache->GUID_index_attribute) == 0)) { int ret; struct ldb_context *ldb = ldb_module_get_ctx(module); list->dn = talloc_array(list, struct ldb_val, 1); if (list->dn == NULL) { ldb_module_oom(module); return LDB_ERR_OPERATIONS_ERROR; } /* * We need to go via the canonicalise_fn() to * ensure we get the index in binary, rather * than a string */ ret = ldb_kv->GUID_index_syntax->canonicalise_fn( ldb, list->dn, &tree->u.equality.value, &list->dn[0]); if (ret != LDB_SUCCESS) { return LDB_ERR_OPERATIONS_ERROR; } list->count = 1; return LDB_SUCCESS; } return ldb_kv_index_dn_simple(module, ldb_kv, tree, list); }
0
libxml2
f0709e3ca8f8947f2d91ed34e92e38a4c23eae63
NOT_APPLICABLE
NOT_APPLICABLE
xz_reset(xz_statep state) { state->have = 0; /* no output data available */ state->eof = 0; /* not at end of file */ state->how = LOOK; /* look for gzip header */ state->direct = 1; /* default for empty file */ state->seek = 0; /* no seek request pending */ xz_error(state, LZMA_OK, NULL); /* clear error */ state->pos = 0; /* no uncompressed data yet */ state->strm.avail_in = 0; /* no input data yet */ #ifdef HAVE_ZLIB_H state->zstrm.avail_in = 0; /* no input data yet */ #endif }
0
dbus
9a6bce9b615abca6068348c1606ba8eaf13d9ae0
CVE-2010-1172
CWE-264
my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error) { if (x + 1 > 10) { g_set_error (error, MY_OBJECT_ERROR, MY_OBJECT_ERROR_FOO, "%s", "x is bigger than 9"); return FALSE; } return x + 1; }
1
Chrome
5d78b84d39bd34bc9fce9d01c0dcd5a22a330d34
NOT_APPLICABLE
NOT_APPLICABLE
gfx::Rect LayerTreeHostImpl::DeviceViewport() const { if (external_viewport_.IsEmpty()) return gfx::Rect(device_viewport_size_); return external_viewport_; }
0
tensorflow
1361fb7e29449629e1df94d44e0427ebec8c83c7
NOT_APPLICABLE
NOT_APPLICABLE
Status InferenceContext::Subshape(ShapeHandle s, int64_t start, int64_t end, ShapeHandle* out) { return Subshape(s, start, end, 1 /* stride */, out); }
0
Chrome
9eb1fd426a04adac0906c81ed88f1089969702ba
NOT_APPLICABLE
NOT_APPLICABLE
void PromptBrowserLoginFunction::OnLoginSuccess() { ProfileSyncService* service = GetSyncService(GetDefaultProfile(profile_)); syncable::ModelTypeSet types; if (service->HasSyncSetupCompleted()) service->GetPreferredDataTypes(&types); types.insert(syncable::APPS); service->ChangePreferredDataTypes(types); service->SetSyncSetupCompleted(); waiting_for_token_ = true; }
0
openjpeg
5d00b719f4b93b1445e6fb4c766b9a9883c57949
NOT_APPLICABLE
NOT_APPLICABLE
void opj_pi_update_encode_poc_and_final ( opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs+1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE = l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; /* special treatment for the first element*/ l_current_poc->layS = 0; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; for (pino = 1;pino < l_poc_bound ; ++pino) { l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE= l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; /* special treatment here different from the first element*/ l_current_poc->layS = (l_current_poc->layE > (l_current_poc-1)->layE) ? l_current_poc->layE : 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } }
0
ImageMagick
53c1dcd34bed85181b901bfce1a2322f85a59472
NOT_APPLICABLE
NOT_APPLICABLE
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]; 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); }
0
poppler
cdb7ad95f7c8fbf63ade040d8a07ec96467042fc
NOT_APPLICABLE
NOT_APPLICABLE
int FoFiTrueType::getNumCmaps() { return nCmaps; }
0
linux
4efbc454ba68def5ef285b26ebfcfdb605b52755
NOT_APPLICABLE
NOT_APPLICABLE
void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags) { const struct sched_class *class; if (p->sched_class == rq->curr->sched_class) { rq->curr->sched_class->check_preempt_curr(rq, p, flags); } else { for_each_class(class) { if (class == rq->curr->sched_class) break; if (class == p->sched_class) { resched_task(rq->curr); break; } } } /* * A queue event has occurred, and we're going to schedule. In * this case, we can save a useless back to back clock update. */ if (rq->curr->on_rq && test_tsk_need_resched(rq->curr)) rq->skip_clock_update = 1; }
0
linux
77f8269606bf95fcb232ee86f6da80886f1dfae8
NOT_APPLICABLE
NOT_APPLICABLE
int ipmi_get_version(struct ipmi_user *user, unsigned char *major, unsigned char *minor) { struct ipmi_device_id id; int rv, index; user = acquire_ipmi_user(user, &index); if (!user) return -ENODEV; rv = bmc_get_device_id(user->intf, NULL, &id, NULL, NULL); if (!rv) { *major = ipmi_version_major(&id); *minor = ipmi_version_minor(&id); } release_ipmi_user(user, index); return rv; }
0
Android
aeea52da00d210587fb3ed895de3d5f2e0264c88
NOT_APPLICABLE
NOT_APPLICABLE
int LvmBundle_process(LVM_INT16 *pIn, LVM_INT16 *pOut, int frameCount, EffectContext *pContext){ LVM_ControlParams_t ActiveParams; /* Current control Parameters */ LVM_ReturnStatus_en LvmStatus = LVM_SUCCESS; /* Function call status */ LVM_INT16 *pOutTmp; if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_WRITE){ pOutTmp = pOut; }else if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE){ if (pContext->pBundledContext->frameCount != frameCount) { if (pContext->pBundledContext->workBuffer != NULL) { free(pContext->pBundledContext->workBuffer); } pContext->pBundledContext->workBuffer = (LVM_INT16 *)malloc(frameCount * sizeof(LVM_INT16) * 2); pContext->pBundledContext->frameCount = frameCount; } pOutTmp = pContext->pBundledContext->workBuffer; }else{ ALOGV("LVM_ERROR : LvmBundle_process invalid access mode"); return -EINVAL; } #ifdef LVM_PCM fwrite(pIn, frameCount*sizeof(LVM_INT16)*2, 1, pContext->pBundledContext->PcmInPtr); fflush(pContext->pBundledContext->PcmInPtr); #endif /* Process the samples */ LvmStatus = LVM_Process(pContext->pBundledContext->hInstance, /* Instance handle */ pIn, /* Input buffer */ pOutTmp, /* Output buffer */ (LVM_UINT16)frameCount, /* Number of samples to read */ 0); /* Audo Time */ LVM_ERROR_CHECK(LvmStatus, "LVM_Process", "LvmBundle_process") if(LvmStatus != LVM_SUCCESS) return -EINVAL; #ifdef LVM_PCM fwrite(pOutTmp, frameCount*sizeof(LVM_INT16)*2, 1, pContext->pBundledContext->PcmOutPtr); fflush(pContext->pBundledContext->PcmOutPtr); #endif if (pContext->config.outputCfg.accessMode == EFFECT_BUFFER_ACCESS_ACCUMULATE){ for (int i=0; i<frameCount*2; i++){ pOut[i] = clamp16((LVM_INT32)pOut[i] + (LVM_INT32)pOutTmp[i]); } } return 0; } /* end LvmBundle_process */
0
unixODBC
45ef78e037f578b15fc58938a3a3251655e71d6f#diff-d52750c7ba4e594410438569d8e2963aL24
CVE-2018-7485
CWE-119
static int ExecuteSQL( SQLHDBC hDbc, char *szSQL, char cDelimiter, int bColumnNames, int bHTMLTable ) { SQLHSTMT hStmt; SQLTCHAR szSepLine[32001]; SQLTCHAR szUcSQL[32001]; SQLSMALLINT cols; SQLINTEGER ret; SQLLEN nRows = 0; szSepLine[ 0 ] = 0; ansi_to_unicode( szSQL, szUcSQL ); /**************************** * EXECUTE SQL ***************************/ if ( SQLAllocStmt( hDbc, &hStmt ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, 0 ); fprintf( stderr, "[ISQL]ERROR: Could not SQLAllocStmt\n" ); return 0; } if ( buseED ) { ret = SQLExecDirect( hStmt, szUcSQL, SQL_NTS ); if ( ret == SQL_NO_DATA ) { fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_NO_DATA\n" ); } else if ( ret == SQL_SUCCESS_WITH_INFO ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]INFO: SQLExecDirect returned SQL_SUCCESS_WITH_INFO\n" ); } else if ( ret != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLExecDirect\n" ); SQLFreeStmt( hStmt, SQL_DROP ); free(szSepLine); return 0; } } else { if ( SQLPrepare( hStmt, szUcSQL, SQL_NTS ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLPrepare\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } ret = SQLExecute( hStmt ); if ( ret == SQL_NO_DATA ) { fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_NO_DATA\n" ); } else if ( ret == SQL_SUCCESS_WITH_INFO ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]INFO: SQLExecute returned SQL_SUCCESS_WITH_INFO\n" ); } else if ( ret != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLExecute\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } } do { /* * check to see if it has generated a result set */ if ( SQLNumResultCols( hStmt, &cols ) != SQL_SUCCESS ) { if ( bVerbose ) DumpODBCLog( hEnv, hDbc, hStmt ); fprintf( stderr, "[ISQL]ERROR: Could not SQLNumResultCols\n" ); SQLFreeStmt( hStmt, SQL_DROP ); return 0; } if ( cols > 0 ) { /**************************** * WRITE HEADER ***************************/ if ( bHTMLTable ) WriteHeaderHTMLTable( hStmt ); else if ( cDelimiter == 0 ) UWriteHeaderNormal( hStmt, szSepLine ); else if ( cDelimiter && bColumnNames ) WriteHeaderDelimited( hStmt, cDelimiter ); /**************************** * WRITE BODY ***************************/ if ( bHTMLTable ) WriteBodyHTMLTable( hStmt ); else if ( cDelimiter == 0 ) nRows = WriteBodyNormal( hStmt ); else WriteBodyDelimited( hStmt, cDelimiter ); } /**************************** * WRITE FOOTER ***************************/ if ( bHTMLTable ) WriteFooterHTMLTable( hStmt ); else if ( cDelimiter == 0 ) UWriteFooterNormal( hStmt, szSepLine, nRows ); } while ( SQL_SUCCEEDED( SQLMoreResults( hStmt ))); /**************************** * CLEANUP ***************************/ SQLFreeStmt( hStmt, SQL_DROP ); return 1; }
1
FFmpeg
454a11a1c9c686c78aa97954306fb63453299760
NOT_APPLICABLE
NOT_APPLICABLE
static void add_8x8basis_c(int16_t rem[64], int16_t basis[64], int scale){ int i; for(i=0; i<8*8; i++){ rem[i] += (basis[i]*scale + (1<<(BASIS_SHIFT - RECON_SHIFT-1)))>>(BASIS_SHIFT - RECON_SHIFT); } }
0
savannah
c265cad1c95b84abfd4e8d861f25926ef13b5d91
NOT_APPLICABLE
NOT_APPLICABLE
irc_server_auto_connect () { struct t_irc_server *ptr_server; for (ptr_server = irc_servers; ptr_server; ptr_server = ptr_server->next_server) { if (IRC_SERVER_OPTION_BOOLEAN(ptr_server, IRC_SERVER_OPTION_AUTOCONNECT)) { if (!irc_server_connect (ptr_server)) irc_server_reconnect_schedule (ptr_server); } } }
0
linux
5872331b3d91820e14716632ebb56b1399b34fe1
NOT_APPLICABLE
NOT_APPLICABLE
static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags) { handle_t *handle = NULL; struct ext4_renament old = { .dir = old_dir, .dentry = old_dentry, .inode = d_inode(old_dentry), }; struct ext4_renament new = { .dir = new_dir, .dentry = new_dentry, .inode = d_inode(new_dentry), }; int force_reread; int retval; struct inode *whiteout = NULL; int credits; u8 old_file_type; if (new.inode && new.inode->i_nlink == 0) { EXT4_ERROR_INODE(new.inode, "target of rename is already freed"); return -EFSCORRUPTED; } if ((ext4_test_inode_flag(new_dir, EXT4_INODE_PROJINHERIT)) && (!projid_eq(EXT4_I(new_dir)->i_projid, EXT4_I(old_dentry->d_inode)->i_projid))) return -EXDEV; retval = dquot_initialize(old.dir); if (retval) return retval; retval = dquot_initialize(new.dir); if (retval) return retval; /* Initialize quotas before so that eventual writes go * in separate transaction */ if (new.inode) { retval = dquot_initialize(new.inode); if (retval) return retval; } old.bh = ext4_find_entry(old.dir, &old.dentry->d_name, &old.de, NULL); if (IS_ERR(old.bh)) return PTR_ERR(old.bh); /* * Check for inode number is _not_ due to possible IO errors. * We might rmdir the source, keep it as pwd of some process * and merrily kill the link to whatever was created under the * same name. Goodbye sticky bit ;-< */ retval = -ENOENT; if (!old.bh || le32_to_cpu(old.de->inode) != old.inode->i_ino) goto end_rename; new.bh = ext4_find_entry(new.dir, &new.dentry->d_name, &new.de, &new.inlined); if (IS_ERR(new.bh)) { retval = PTR_ERR(new.bh); new.bh = NULL; goto end_rename; } if (new.bh) { if (!new.inode) { brelse(new.bh); new.bh = NULL; } } if (new.inode && !test_opt(new.dir->i_sb, NO_AUTO_DA_ALLOC)) ext4_alloc_da_blocks(old.inode); credits = (2 * EXT4_DATA_TRANS_BLOCKS(old.dir->i_sb) + EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2); if (!(flags & RENAME_WHITEOUT)) { handle = ext4_journal_start(old.dir, EXT4_HT_DIR, credits); if (IS_ERR(handle)) { retval = PTR_ERR(handle); handle = NULL; goto end_rename; } } else { whiteout = ext4_whiteout_for_rename(&old, credits, &handle); if (IS_ERR(whiteout)) { retval = PTR_ERR(whiteout); whiteout = NULL; goto end_rename; } } if (IS_DIRSYNC(old.dir) || IS_DIRSYNC(new.dir)) ext4_handle_sync(handle); if (S_ISDIR(old.inode->i_mode)) { if (new.inode) { retval = -ENOTEMPTY; if (!ext4_empty_dir(new.inode)) goto end_rename; } else { retval = -EMLINK; if (new.dir != old.dir && EXT4_DIR_LINK_MAX(new.dir)) goto end_rename; } retval = ext4_rename_dir_prepare(handle, &old); if (retval) goto end_rename; } /* * If we're renaming a file within an inline_data dir and adding or * setting the new dirent causes a conversion from inline_data to * extents/blockmap, we need to force the dirent delete code to * re-read the directory, or else we end up trying to delete a dirent * from what is now the extent tree root (or a block map). */ force_reread = (new.dir->i_ino == old.dir->i_ino && ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA)); old_file_type = old.de->file_type; if (whiteout) { /* * Do this before adding a new entry, so the old entry is sure * to be still pointing to the valid old entry. */ retval = ext4_setent(handle, &old, whiteout->i_ino, EXT4_FT_CHRDEV); if (retval) goto end_rename; retval = ext4_mark_inode_dirty(handle, whiteout); if (unlikely(retval)) goto end_rename; } if (!new.bh) { retval = ext4_add_entry(handle, new.dentry, old.inode); if (retval) goto end_rename; } else { retval = ext4_setent(handle, &new, old.inode->i_ino, old_file_type); if (retval) goto end_rename; } if (force_reread) force_reread = !ext4_test_inode_flag(new.dir, EXT4_INODE_INLINE_DATA); /* * Like most other Unix systems, set the ctime for inodes on a * rename. */ old.inode->i_ctime = current_time(old.inode); retval = ext4_mark_inode_dirty(handle, old.inode); if (unlikely(retval)) goto end_rename; if (!whiteout) { /* * ok, that's it */ ext4_rename_delete(handle, &old, force_reread); } if (new.inode) { ext4_dec_count(handle, new.inode); new.inode->i_ctime = current_time(new.inode); } old.dir->i_ctime = old.dir->i_mtime = current_time(old.dir); ext4_update_dx_flag(old.dir); if (old.dir_bh) { retval = ext4_rename_dir_finish(handle, &old, new.dir->i_ino); if (retval) goto end_rename; ext4_dec_count(handle, old.dir); if (new.inode) { /* checked ext4_empty_dir above, can't have another * parent, ext4_dec_count() won't work for many-linked * dirs */ clear_nlink(new.inode); } else { ext4_inc_count(handle, new.dir); ext4_update_dx_flag(new.dir); retval = ext4_mark_inode_dirty(handle, new.dir); if (unlikely(retval)) goto end_rename; } } retval = ext4_mark_inode_dirty(handle, old.dir); if (unlikely(retval)) goto end_rename; if (new.inode) { retval = ext4_mark_inode_dirty(handle, new.inode); if (unlikely(retval)) goto end_rename; if (!new.inode->i_nlink) ext4_orphan_add(handle, new.inode); } retval = 0; end_rename: brelse(old.dir_bh); brelse(old.bh); brelse(new.bh); if (whiteout) { if (retval) drop_nlink(whiteout); unlock_new_inode(whiteout); iput(whiteout); } if (handle) ext4_journal_stop(handle); return retval; }
0
libidn
570e68886c41c2e765e6218cb317d9a9a447a041
NOT_APPLICABLE
NOT_APPLICABLE
getline (char **lineptr, size_t *n, FILE *stream) { return getdelim (lineptr, n, '\n', stream); }
0
php-src
7cf7148a8f8f4f55fb04de2a517d740bb6253eac
NOT_APPLICABLE
NOT_APPLICABLE
static php_iconv_err_t _php_iconv_strpos(size_t *pretval, const char *haystk, size_t haystk_nbytes, const char *ndl, size_t ndl_nbytes, zend_long offset, const char *enc) { char buf[GENERIC_SUPERSET_NBYTES]; php_iconv_err_t err = PHP_ICONV_ERR_SUCCESS; iconv_t cd; const char *in_p; size_t in_left; char *out_p; size_t out_left; size_t cnt; zend_string *ndl_buf; const char *ndl_buf_p; size_t ndl_buf_left; size_t match_ofs; *pretval = (size_t)-1; err = php_iconv_string(ndl, ndl_nbytes, &ndl_buf, GENERIC_SUPERSET_NAME, enc); if (err != PHP_ICONV_ERR_SUCCESS) { if (ndl_buf != NULL) { zend_string_free(ndl_buf); } return err; } cd = iconv_open(GENERIC_SUPERSET_NAME, enc); if (cd == (iconv_t)(-1)) { if (ndl_buf != NULL) { zend_string_free(ndl_buf); } #if ICONV_SUPPORTS_ERRNO if (errno == EINVAL) { return PHP_ICONV_ERR_WRONG_CHARSET; } else { return PHP_ICONV_ERR_CONVERTER; } #else return PHP_ICONV_ERR_UNKNOWN; #endif } ndl_buf_p = ZSTR_VAL(ndl_buf); ndl_buf_left = ZSTR_LEN(ndl_buf); match_ofs = (size_t)-1; for (in_p = haystk, in_left = haystk_nbytes, cnt = 0; in_left > 0; ++cnt) { size_t prev_in_left; out_p = buf; out_left = sizeof(buf); prev_in_left = in_left; if (iconv(cd, (char **)&in_p, &in_left, (char **) &out_p, &out_left) == (size_t)-1) { if (prev_in_left == in_left) { #if ICONV_SUPPORTS_ERRNO switch (errno) { case EINVAL: err = PHP_ICONV_ERR_ILLEGAL_CHAR; break; case EILSEQ: err = PHP_ICONV_ERR_ILLEGAL_SEQ; break; case E2BIG: break; default: err = PHP_ICONV_ERR_UNKNOWN; break; } #endif break; } } if (offset >= 0) { if (cnt >= (size_t)offset) { if (_php_iconv_memequal(buf, ndl_buf_p, sizeof(buf))) { if (match_ofs == (size_t)-1) { match_ofs = cnt; } ndl_buf_p += GENERIC_SUPERSET_NBYTES; ndl_buf_left -= GENERIC_SUPERSET_NBYTES; if (ndl_buf_left == 0) { *pretval = match_ofs; break; } } else { size_t i, j, lim; i = 0; j = GENERIC_SUPERSET_NBYTES; lim = (size_t)(ndl_buf_p - ZSTR_VAL(ndl_buf)); while (j < lim) { if (_php_iconv_memequal(&ZSTR_VAL(ndl_buf)[j], &ZSTR_VAL(ndl_buf)[i], GENERIC_SUPERSET_NBYTES)) { i += GENERIC_SUPERSET_NBYTES; } else { j -= i; i = 0; } j += GENERIC_SUPERSET_NBYTES; } if (_php_iconv_memequal(buf, &ZSTR_VAL(ndl_buf)[i], sizeof(buf))) { match_ofs += (lim - i) / GENERIC_SUPERSET_NBYTES; i += GENERIC_SUPERSET_NBYTES; ndl_buf_p = &ZSTR_VAL(ndl_buf)[i]; ndl_buf_left = ZSTR_LEN(ndl_buf) - i; } else { match_ofs = (size_t)-1; ndl_buf_p = ZSTR_VAL(ndl_buf); ndl_buf_left = ZSTR_LEN(ndl_buf); } } } } else { if (_php_iconv_memequal(buf, ndl_buf_p, sizeof(buf))) { if (match_ofs == (size_t)-1) { match_ofs = cnt; } ndl_buf_p += GENERIC_SUPERSET_NBYTES; ndl_buf_left -= GENERIC_SUPERSET_NBYTES; if (ndl_buf_left == 0) { *pretval = match_ofs; ndl_buf_p = ZSTR_VAL(ndl_buf); ndl_buf_left = ZSTR_LEN(ndl_buf); match_ofs = -1; } } else { size_t i, j, lim; i = 0; j = GENERIC_SUPERSET_NBYTES; lim = (size_t)(ndl_buf_p - ZSTR_VAL(ndl_buf)); while (j < lim) { if (_php_iconv_memequal(&ZSTR_VAL(ndl_buf)[j], &ZSTR_VAL(ndl_buf)[i], GENERIC_SUPERSET_NBYTES)) { i += GENERIC_SUPERSET_NBYTES; } else { j -= i; i = 0; } j += GENERIC_SUPERSET_NBYTES; } if (_php_iconv_memequal(buf, &ZSTR_VAL(ndl_buf)[i], sizeof(buf))) { match_ofs += (lim - i) / GENERIC_SUPERSET_NBYTES; i += GENERIC_SUPERSET_NBYTES; ndl_buf_p = &ZSTR_VAL(ndl_buf)[i]; ndl_buf_left = ZSTR_LEN(ndl_buf) - i; } else { match_ofs = (size_t)-1; ndl_buf_p = ZSTR_VAL(ndl_buf); ndl_buf_left = ZSTR_LEN(ndl_buf); } } } } if (ndl_buf) { zend_string_free(ndl_buf); } iconv_close(cd); return err; }
0
Android
c894aa36be535886a8e5ff02cdbcd07dd24618f6
NOT_APPLICABLE
NOT_APPLICABLE
status_t AudioFlinger::EffectModule::setDevice(audio_devices_t device) { if (device == AUDIO_DEVICE_NONE) { return NO_ERROR; } Mutex::Autolock _l(mLock); if (mStatus != NO_ERROR) { return mStatus; } status_t status = NO_ERROR; if ((mDescriptor.flags & EFFECT_FLAG_DEVICE_MASK) == EFFECT_FLAG_DEVICE_IND) { status_t cmdStatus; uint32_t size = sizeof(status_t); uint32_t cmd = audio_is_output_devices(device) ? EFFECT_CMD_SET_DEVICE : EFFECT_CMD_SET_INPUT_DEVICE; status = (*mEffectInterface)->command(mEffectInterface, cmd, sizeof(uint32_t), &device, &size, &cmdStatus); } return status; }
0
linux
394f56fe480140877304d342dec46d50dc823d46
NOT_APPLICABLE
NOT_APPLICABLE
int compat_arch_setup_additional_pages(struct linux_binprm *bprm, int uses_interp) { #ifdef CONFIG_X86_X32_ABI if (test_thread_flag(TIF_X32)) { if (!vdso64_enabled) return 0; return map_vdso(&vdso_image_x32, true); } #endif return load_vdso32(); }
0
linux
b9a41d21dceadf8104812626ef85dc56ee8a60ed
NOT_APPLICABLE
NOT_APPLICABLE
int dm_cancel_deferred_remove(struct mapped_device *md) { int r = 0; spin_lock(&_minor_lock); if (test_bit(DMF_DELETING, &md->flags)) r = -EBUSY; else clear_bit(DMF_DEFERRED_REMOVE, &md->flags); spin_unlock(&_minor_lock); return r; }
0
php-src
abd159cce48f3e34f08e4751c568e09677d5ec9c
NOT_APPLICABLE
NOT_APPLICABLE
PHPAPI void php_fgetcsv(php_stream *stream, char delimiter, char enclosure, char escape_char, size_t buf_len, char *buf, zval *return_value TSRMLS_DC) /* {{{ */ { char *temp, *tptr, *bptr, *line_end, *limit; size_t temp_len, line_end_len; int inc_len; zend_bool first_field = 1; /* initialize internal state */ php_ignore_value(php_mblen(NULL, 0)); /* Now into new section that parses buf for delimiter/enclosure fields */ /* Strip trailing space from buf, saving end of line in case required for enclosure field */ bptr = buf; tptr = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len, delimiter TSRMLS_CC); line_end_len = buf_len - (size_t)(tptr - buf); line_end = limit = tptr; /* reserve workspace for building each individual field */ temp_len = buf_len; temp = emalloc(temp_len + line_end_len + 1); /* Initialize return array */ array_init(return_value); /* Main loop to read CSV fields */ /* NB this routine will return a single null entry for a blank line */ do { char *comp_end, *hunk_begin; tptr = temp; inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); if (inc_len == 1) { char *tmp = bptr; while ((*tmp != delimiter) && isspace((int)*(unsigned char *)tmp)) { tmp++; } if (*tmp == enclosure) { bptr = tmp; } } if (first_field && bptr == line_end) { add_next_index_null(return_value); break; } first_field = 0; /* 2. Read field, leaving bptr pointing at start of next field */ if (inc_len != 0 && *bptr == enclosure) { int state = 0; bptr++; /* move on to first character in field */ hunk_begin = bptr; /* 2A. handle enclosure delimited field */ for (;;) { switch (inc_len) { case 0: switch (state) { case 2: memcpy(tptr, hunk_begin, bptr - hunk_begin - 1); tptr += (bptr - hunk_begin - 1); hunk_begin = bptr; goto quit_loop_2; case 1: memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); hunk_begin = bptr; /* break is omitted intentionally */ case 0: { char *new_buf; size_t new_len; char *new_temp; if (hunk_begin != line_end) { memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); hunk_begin = bptr; } /* add the embedded line end to the field */ memcpy(tptr, line_end, line_end_len); tptr += line_end_len; if (stream == NULL) { goto quit_loop_2; } else if ((new_buf = php_stream_get_line(stream, NULL, 0, &new_len)) == NULL) { /* we've got an unterminated enclosure, * assign all the data from the start of * the enclosure to end of data to the * last element */ if ((size_t)temp_len > (size_t)(limit - buf)) { goto quit_loop_2; } zval_dtor(return_value); RETVAL_FALSE; goto out; } temp_len += new_len; new_temp = erealloc(temp, temp_len); tptr = new_temp + (size_t)(tptr - temp); temp = new_temp; efree(buf); buf_len = new_len; bptr = buf = new_buf; hunk_begin = buf; line_end = limit = (char *)php_fgetcsv_lookup_trailing_spaces(buf, buf_len, delimiter TSRMLS_CC); line_end_len = buf_len - (size_t)(limit - buf); state = 0; } break; } break; case -2: case -1: php_ignore_value(php_mblen(NULL, 0)); /* break is omitted intentionally */ case 1: /* we need to determine if the enclosure is * 'real' or is it escaped */ switch (state) { case 1: /* escaped */ bptr++; state = 0; break; case 2: /* embedded enclosure ? let's check it */ if (*bptr != enclosure) { /* real enclosure */ memcpy(tptr, hunk_begin, bptr - hunk_begin - 1); tptr += (bptr - hunk_begin - 1); hunk_begin = bptr; goto quit_loop_2; } memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); bptr++; hunk_begin = bptr; state = 0; break; default: if (*bptr == enclosure) { state = 2; } else if (*bptr == escape_char) { state = 1; } bptr++; break; } break; default: switch (state) { case 2: /* real enclosure */ memcpy(tptr, hunk_begin, bptr - hunk_begin - 1); tptr += (bptr - hunk_begin - 1); hunk_begin = bptr; goto quit_loop_2; case 1: bptr += inc_len; memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); hunk_begin = bptr; break; default: bptr += inc_len; break; } break; } inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); } quit_loop_2: /* look up for a delimiter */ for (;;) { switch (inc_len) { case 0: goto quit_loop_3; case -2: case -1: inc_len = 1; php_ignore_value(php_mblen(NULL, 0)); /* break is omitted intentionally */ case 1: if (*bptr == delimiter) { goto quit_loop_3; } break; default: break; } bptr += inc_len; inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); } quit_loop_3: memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); bptr += inc_len; comp_end = tptr; } else { /* 2B. Handle non-enclosure field */ hunk_begin = bptr; for (;;) { switch (inc_len) { case 0: goto quit_loop_4; case -2: case -1: inc_len = 1; php_ignore_value(php_mblen(NULL, 0)); /* break is omitted intentionally */ case 1: if (*bptr == delimiter) { goto quit_loop_4; } break; default: break; } bptr += inc_len; inc_len = (bptr < limit ? (*bptr == '\0' ? 1: php_mblen(bptr, limit - bptr)): 0); } quit_loop_4: memcpy(tptr, hunk_begin, bptr - hunk_begin); tptr += (bptr - hunk_begin); comp_end = (char *)php_fgetcsv_lookup_trailing_spaces(temp, tptr - temp, delimiter TSRMLS_CC); if (*bptr == delimiter) { bptr++; } } /* 3. Now pass our field back to php */ *comp_end = '\0'; add_next_index_stringl(return_value, temp, comp_end - temp, 1); } while (inc_len > 0); out: efree(temp); if (stream) { efree(buf); } }
0
hhvm
1888810e77b446a79a7674784d5f139fcfa605e2
NOT_APPLICABLE
NOT_APPLICABLE
size_t operator()(const ArrayOrObject data) const { return data.toOpaque(); }
0
linux
263b4509ec4d47e0da3e753f85a39ea12d1eff24
NOT_APPLICABLE
NOT_APPLICABLE
int nfs_wb_page_cancel(struct inode *inode, struct page *page) { struct nfs_page *req; int ret = 0; for (;;) { wait_on_page_writeback(page); req = nfs_page_find_request(page); if (req == NULL) break; if (nfs_lock_request(req)) { nfs_clear_request_commit(req); nfs_inode_remove_request(req); /* * In case nfs_inode_remove_request has marked the * page as being dirty */ cancel_dirty_page(page, PAGE_CACHE_SIZE); nfs_unlock_and_release_request(req); break; } ret = nfs_wait_on_request(req); nfs_release_request(req); if (ret < 0) break; } return ret; }
0
krb5
a197e92349a4aa2141b5dff12e9dd44c2a2166e3
NOT_APPLICABLE
NOT_APPLICABLE
xdr_gstrings_ret(XDR *xdrs, gstrings_ret *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_kadm5_ret_t(xdrs, &objp->code)) { return (FALSE); } if (objp->code == KADM5_OK) { if (!xdr_int(xdrs, &objp->count)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *) &objp->strings, (unsigned int *) &objp->count, ~0, sizeof(krb5_string_attr), xdr_krb5_string_attr)) { return (FALSE); } } return (TRUE); }
0
linux
0048b4837affd153897ed1222283492070027aa9
CVE-2015-9016
CWE-362
static void bt_for_each(struct blk_mq_hw_ctx *hctx, struct blk_mq_bitmap_tags *bt, unsigned int off, busy_iter_fn *fn, void *data, bool reserved) { struct request *rq; int bit, i; for (i = 0; i < bt->map_nr; i++) { struct blk_align_bitmap *bm = &bt->map[i]; for (bit = find_first_bit(&bm->word, bm->depth); bit < bm->depth; bit = find_next_bit(&bm->word, bm->depth, bit + 1)) { rq = blk_mq_tag_to_rq(hctx->tags, off + bit); if (rq->q == hctx->queue) fn(hctx, rq, data, reserved); } off += (1 << bt->bits_per_word); } }
1
qemu
d68f0f778e7f4fbd674627274267f269e40f0b04
NOT_APPLICABLE
NOT_APPLICABLE
static int handle_cmd(AHCIState *s, int port, uint8_t slot) { IDEState *ide_state; uint64_t tbl_addr; AHCICmdHdr *cmd; uint8_t *cmd_fis; dma_addr_t cmd_len; if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) { /* Engine currently busy, try again later */ DPRINTF(port, "engine busy\n"); return -1; } if (!s->dev[port].lst) { DPRINTF(port, "error: lst not given but cmd handled"); return -1; } cmd = get_cmd_header(s, port, slot); /* remember current slot handle for later */ s->dev[port].cur_cmd = cmd; /* The device we are working for */ ide_state = &s->dev[port].port.ifs[0]; if (!ide_state->blk) { DPRINTF(port, "error: guest accessed unused port"); return -1; } tbl_addr = le64_to_cpu(cmd->tbl_addr); cmd_len = 0x80; cmd_fis = dma_memory_map(s->as, tbl_addr, &cmd_len, DMA_DIRECTION_FROM_DEVICE); if (!cmd_fis) { DPRINTF(port, "error: guest passed us an invalid cmd fis\n"); return -1; } else if (cmd_len != 0x80) { ahci_trigger_irq(s, &s->dev[port], PORT_IRQ_HBUS_ERR); DPRINTF(port, "error: dma_memory_map failed: " "(len(%02"PRIx64") != 0x80)\n", cmd_len); goto out; } debug_print_fis(cmd_fis, 0x80); switch (cmd_fis[0]) { case SATA_FIS_TYPE_REGISTER_H2D: handle_reg_h2d_fis(s, port, slot, cmd_fis); break; default: DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x " "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1], cmd_fis[2]); break; } out: dma_memory_unmap(s->as, cmd_fis, cmd_len, DMA_DIRECTION_FROM_DEVICE, cmd_len); if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) { /* async command, complete later */ s->dev[port].busy_slot = slot; return -1; } /* done handling the command */ return 0; }
0
tensorflow
f8378920345f4f4604202d4ab15ef64b2aceaa16
NOT_APPLICABLE
NOT_APPLICABLE
bool HasDynamicTensorImpl(const TfLiteContext& context, const TensorIntArray& int_array) { for (int i : int_array) { if (i == kTfLiteOptionalTensor) continue; const TfLiteTensor& tensor = context.tensors[i]; if (tensor.allocation_type == kTfLiteDynamic) { return true; } } return false; }
0
Chrome
aa1a102f73565feeb1d121d0d6c9524bebcdd75f
NOT_APPLICABLE
NOT_APPLICABLE
SecurityOrigin* XMLHttpRequest::securityOrigin() const { return m_securityOrigin ? m_securityOrigin.get() : scriptExecutionContext()->securityOrigin(); }
0
linux
f2815633504b442ca0b0605c16bf3d88a3a0fcea
NOT_APPLICABLE
NOT_APPLICABLE
static sctp_disposition_t sctp_sf_violation_paramlen( struct net *net, const struct sctp_endpoint *ep, const struct sctp_association *asoc, const sctp_subtype_t type, void *arg, void *ext, sctp_cmd_seq_t *commands) { struct sctp_chunk *chunk = arg; struct sctp_paramhdr *param = ext; struct sctp_chunk *abort = NULL; if (sctp_auth_recv_cid(SCTP_CID_ABORT, asoc)) goto discard; /* Make the abort chunk. */ abort = sctp_make_violation_paramlen(asoc, chunk, param); if (!abort) goto nomem; sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(abort)); SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); sctp_add_cmd_sf(commands, SCTP_CMD_SET_SK_ERR, SCTP_ERROR(ECONNABORTED)); sctp_add_cmd_sf(commands, SCTP_CMD_ASSOC_FAILED, SCTP_PERR(SCTP_ERROR_PROTO_VIOLATION)); SCTP_DEC_STATS(net, SCTP_MIB_CURRESTAB); SCTP_INC_STATS(net, SCTP_MIB_ABORTEDS); discard: sctp_sf_pdiscard(net, ep, asoc, SCTP_ST_CHUNK(0), arg, commands); return SCTP_DISPOSITION_ABORT; nomem: return SCTP_DISPOSITION_NOMEM; }
0
rsyslog
80f88242982c9c6ad6ce8628fc5b94ea74051cf4
NOT_APPLICABLE
NOT_APPLICABLE
setBaseURL(instanceData *pData, es_str_t **url) { char portBuf[64]; int r; DEFiRet; *url = es_newStr(128); snprintf(portBuf, sizeof(portBuf), "%d", pData->port); r = es_addBuf(url, "http://", sizeof("http://")-1); if(r == 0) r = es_addBuf(url, (char*)pData->server, strlen((char*)pData->server)); if(r == 0) r = es_addChar(url, ':'); if(r == 0) r = es_addBuf(url, portBuf, strlen(portBuf)); if(r == 0) r = es_addChar(url, '/'); RETiRet; }
0
qemu
d3b0db6dfea6b3a9ee0d96aceb796bdcafa84314
NOT_APPLICABLE
NOT_APPLICABLE
static int vnc_display_get_address(const char *addrstr, bool websocket, bool reverse, int displaynum, int to, bool has_ipv4, bool has_ipv6, bool ipv4, bool ipv6, SocketAddress **retaddr, Error **errp) { int ret = -1; SocketAddress *addr = NULL; addr = g_new0(SocketAddress, 1); if (strncmp(addrstr, "unix:", 5) == 0) { addr->type = SOCKET_ADDRESS_TYPE_UNIX; addr->u.q_unix.path = g_strdup(addrstr + 5); if (websocket) { error_setg(errp, "UNIX sockets not supported with websock"); goto cleanup; } if (to) { error_setg(errp, "Port range not support with UNIX socket"); goto cleanup; } ret = 0; } else { const char *port; size_t hostlen; unsigned long long baseport = 0; InetSocketAddress *inet; port = strrchr(addrstr, ':'); if (!port) { if (websocket) { hostlen = 0; port = addrstr; } else { error_setg(errp, "no vnc port specified"); goto cleanup; } } else { hostlen = port - addrstr; port++; if (*port == '\0') { error_setg(errp, "vnc port cannot be empty"); goto cleanup; } } addr->type = SOCKET_ADDRESS_TYPE_INET; inet = &addr->u.inet; if (addrstr[0] == '[' && addrstr[hostlen - 1] == ']') { inet->host = g_strndup(addrstr + 1, hostlen - 2); } else { inet->host = g_strndup(addrstr, hostlen); } /* plain VNC port is just an offset, for websocket * port is absolute */ if (websocket) { if (g_str_equal(addrstr, "") || g_str_equal(addrstr, "on")) { if (displaynum == -1) { error_setg(errp, "explicit websocket port is required"); goto cleanup; } inet->port = g_strdup_printf( "%d", displaynum + 5700); if (to) { inet->has_to = true; inet->to = to + 5700; } } else { inet->port = g_strdup(port); } } else { int offset = reverse ? 0 : 5900; if (parse_uint_full(port, &baseport, 10) < 0) { error_setg(errp, "can't convert to a number: %s", port); goto cleanup; } if (baseport > 65535 || baseport + offset > 65535) { error_setg(errp, "port %s out of range", port); goto cleanup; } inet->port = g_strdup_printf( "%d", (int)baseport + offset); if (to) { inet->has_to = true; inet->to = to + offset; } } inet->ipv4 = ipv4; inet->has_ipv4 = has_ipv4; inet->ipv6 = ipv6; inet->has_ipv6 = has_ipv6; ret = baseport; } *retaddr = addr; cleanup: if (ret < 0) { qapi_free_SocketAddress(addr); } return ret; }
0
savannah
fa481c116e65ccf9137c7ddc8abc3cf05dc12f55
NOT_APPLICABLE
NOT_APPLICABLE
nsPluginInstance::getDocumentProp(const std::string& propname) const { std::string rv; if (!HasScripting()) { LOG_ONCE( gnash::log_debug("Browser doesn't support scripting") ); return rv; } NPObject* windowobj; NPError err = NPN_GetValue(_instance, NPNVWindowNPObject, &windowobj); if (err != NPERR_NO_ERROR || !windowobj) { return rv; } boost::shared_ptr<NPObject> window_obj(windowobj, NPN_ReleaseObject); NPIdentifier doc_id = NPN_GetStringIdentifier("document"); NPVariant docvar; if(! NPN_GetProperty(_instance, windowobj, doc_id, &docvar) ) { return rv; } boost::shared_ptr<NPVariant> doc_var(&docvar, NPN_ReleaseVariantValue); if (!NPVARIANT_IS_OBJECT(docvar)) { return rv; } NPObject* doc_obj = NPVARIANT_TO_OBJECT(docvar); NPIdentifier prop_id = NPN_GetStringIdentifier(propname.c_str()); NPVariant propvar; if (!NPN_GetProperty(_instance, doc_obj, prop_id, &propvar)) { return rv; } boost::shared_ptr<NPVariant> prop_var(&propvar, NPN_ReleaseVariantValue); if (!NPVARIANT_IS_STRING(propvar)) { return rv; } const NPString& prop_str = NPVARIANT_TO_STRING(propvar); rv = NPStringToString(prop_str); return rv; }
0
Chrome
1a90b2996bfd341a04073f0054047073865b485d
NOT_APPLICABLE
NOT_APPLICABLE
void RecordUnsubscribeIIDResult(InstanceID::Result result) { UMA_HISTOGRAM_ENUMERATION("PushMessaging.UnregistrationIIDResult", result, InstanceID::LAST_RESULT + 1); }
0
ImageMagick
e793eb203e5e0f91f5037aed6585e81b1e27395b
NOT_APPLICABLE
NOT_APPLICABLE
static void MSLStartElement(void *context,const xmlChar *tag, const xmlChar **attributes) { AffineMatrix affine, current; ChannelType channel; ChannelType channel_mask; char *attribute, key[MagickPathExtent], *value; const char *keyword; double angle; DrawInfo *draw_info; ExceptionInfo *exception; GeometryInfo geometry_info; Image *image; int flags; ssize_t option, j, n, x, y; MSLInfo *msl_info; RectangleInfo geometry; register ssize_t i; size_t height, width; /* Called when an opening tag has been processed. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " SAX.startElement(%s",tag); exception=AcquireExceptionInfo(); msl_info=(MSLInfo *) context; n=msl_info->n; keyword=(const char *) NULL; value=(char *) NULL; SetGeometryInfo(&geometry_info); (void) ResetMagickMemory(&geometry,0,sizeof(geometry)); channel=DefaultChannels; switch (*tag) { case 'A': case 'a': { if (LocaleCompare((const char *) tag,"add-noise") == 0) { Image *noise_image; NoiseType noise; /* Add noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } noise=UniformNoise; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'N': case 'n': { if (LocaleCompare(keyword,"noise") == 0) { option=ParseCommandOption(MagickNoiseOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); noise=(NoiseType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); noise_image=AddNoiseImage(msl_info->image[n],noise,1.0, msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); if (noise_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=noise_image; break; } if (LocaleCompare((const char *) tag,"annotate") == 0) { char text[MagickPathExtent]; /* Annotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGravityGeometry(msl_info->image[n],value, &geometry,exception); break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=tan(DegreesToRadians(fmod((double) angle, 360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=tan(DegreesToRadians(fmod((double) angle, 360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->stroke,exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { CloneString(&draw_info->text,value); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->undercolor,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; (void) AnnotateImage(msl_info->image[n],draw_info, msl_info->exception); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"append") == 0) { Image *append_image; MagickBooleanType stack; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } stack=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'S': case 's': { if (LocaleCompare(keyword,"stack") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); stack=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } append_image=AppendImages(msl_info->image[n],stack, msl_info->exception); if (append_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=append_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); break; } case 'B': case 'b': { if (LocaleCompare((const char *) tag,"blur") == 0) { Image *blur_image; /* Blur image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); blur_image=BlurImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); if (blur_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=blur_image; break; } if (LocaleCompare((const char *) tag,"border") == 0) { Image *border_image; /* Border image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); msl_info->image[n]->compose=(CompositeOperator) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &msl_info->image[n]->border_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } border_image=BorderImage(msl_info->image[n],&geometry, msl_info->image[n]->compose,msl_info->exception); if (border_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=border_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'C': case 'c': { if (LocaleCompare((const char *) tag,"colorize") == 0) { char blend[MagickPathExtent]; Image *colorize_image; PixelInfo target; /* Add noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } GetPixelInfo(msl_info->image[n],&target); (void) CopyMagickString(blend,"100",MagickPathExtent); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blend") == 0) { (void) CopyMagickString(blend,value,MagickPathExtent); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &target,msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } colorize_image=ColorizeImage(msl_info->image[n],blend,&target, msl_info->exception); if (colorize_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=colorize_image; break; } if (LocaleCompare((const char *) tag, "charcoal") == 0) { double radius = 0.0, sigma = 1.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* NOTE: charcoal can have no attributes, since we use all the defaults! */ if (attributes != (const xmlChar **) NULL) { for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { radius=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { sigma = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } } /* charcoal image. */ { Image *newImage; newImage=CharcoalImage(msl_info->image[n],radius,sigma, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } if (LocaleCompare((const char *) tag,"chop") == 0) { Image *chop_image; /* Chop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } chop_image=ChopImage(msl_info->image[n],&geometry, msl_info->exception); if (chop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=chop_image; break; } if (LocaleCompare((const char *) tag,"color-floodfill") == 0) { PaintMethod paint_method; PixelInfo target; /* Color floodfill image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); SetGeometry(msl_info->image[n],&geometry); paint_method=FloodfillMethod; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"bordercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &target,exception); paint_method=FillToBorderMethod; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FloodfillPaintImage(msl_info->image[n],draw_info,&target, geometry.x,geometry.y,paint_method == FloodfillMethod ? MagickFalse : MagickTrue,msl_info->exception); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"comment") == 0) break; if (LocaleCompare((const char *) tag,"composite") == 0) { char composite_geometry[MagickPathExtent]; CompositeOperator compose; Image *composite_image, *rotate_image; /* Composite image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } composite_image=NewImageList(); compose=OverCompositeOp; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); compose=(CompositeOperator) option; break; } break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { composite_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: break; } } if (composite_image == (Image *) NULL) break; rotate_image=NewImageList(); SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blend") == 0) { (void) SetImageArtifact(composite_image, "compose:args",value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } if (LocaleCompare(keyword, "color") == 0) { (void) QueryColorCompliance(value,AllCompliance, &composite_image->background_color,exception); break; } if (LocaleCompare(keyword,"compose") == 0) break; ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); msl_info->image[n]->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) break; ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'M': case 'm': { if (LocaleCompare(keyword,"mask") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(value,value) == 0)) { SetImageType(composite_image,TrueColorAlphaType, exception); (void) CompositeImage(composite_image, msl_info->image[j],CopyAlphaCompositeOp,MagickTrue, 0,0,exception); break; } } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { ssize_t opacity, y; register ssize_t x; register Quantum *q; CacheView *composite_view; opacity=StringToLong(value); if (compose != DissolveCompositeOp) { (void) SetImageAlpha(composite_image,(Quantum) opacity,exception); break; } (void) SetImageArtifact(msl_info->image[n], "compose:args",value); if (composite_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlpha(composite_image,OpaqueAlpha, exception); composite_view=AcquireAuthenticCacheView(composite_image,exception); for (y=0; y < (ssize_t) composite_image->rows ; y++) { q=GetCacheViewAuthenticPixels(composite_view,0,y, (ssize_t) composite_image->columns,1,exception); for (x=0; x < (ssize_t) composite_image->columns; x++) { if (GetPixelAlpha(composite_image,q) == OpaqueAlpha) SetPixelAlpha(composite_image, ClampToQuantum(opacity),q); q+=GetPixelChannels(composite_image); } if (SyncCacheViewAuthenticPixels(composite_view,exception) == MagickFalse) break; } composite_view=DestroyCacheView(composite_view); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { rotate_image=RotateImage(composite_image, StringToDouble(value,(char **) NULL),exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"tile") == 0) { MagickBooleanType tile; option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); tile=(MagickBooleanType) option; (void) tile; if (rotate_image != (Image *) NULL) (void) SetImageArtifact(rotate_image, "compose:outside-overlay","false"); else (void) SetImageArtifact(composite_image, "compose:outside-overlay","false"); image=msl_info->image[n]; height=composite_image->rows; width=composite_image->columns; for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) height) for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) width) { if (rotate_image != (Image *) NULL) (void) CompositeImage(image,rotate_image,compose, MagickTrue,x,y,exception); else (void) CompositeImage(image,composite_image, compose,MagickTrue,x,y,exception); } if (rotate_image != (Image *) NULL) rotate_image=DestroyImage(rotate_image); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } image=msl_info->image[n]; (void) FormatLocaleString(composite_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns, (double) composite_image->rows,(double) geometry.x,(double) geometry.y); flags=ParseGravityGeometry(image,composite_geometry,&geometry, exception); channel_mask=SetImageChannelMask(image,channel); if (rotate_image == (Image *) NULL) CompositeImage(image,composite_image,compose,MagickTrue,geometry.x, geometry.y,exception); else { /* Rotate image. */ geometry.x-=(ssize_t) (rotate_image->columns- composite_image->columns)/2; geometry.y-=(ssize_t) (rotate_image->rows- composite_image->rows)/2; CompositeImage(image,rotate_image,compose,MagickTrue,geometry.x, geometry.y,exception); rotate_image=DestroyImage(rotate_image); } (void) SetImageChannelMask(image,channel_mask); composite_image=DestroyImage(composite_image); break; } if (LocaleCompare((const char *) tag,"contrast") == 0) { MagickBooleanType sharpen; /* Contrast image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } sharpen=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'S': case 's': { if (LocaleCompare(keyword,"sharpen") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); sharpen=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) ContrastImage(msl_info->image[n],sharpen, msl_info->exception); break; } if (LocaleCompare((const char *) tag,"crop") == 0) { Image *crop_image; /* Crop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGravityGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } crop_image=CropImage(msl_info->image[n],&geometry, msl_info->exception); if (crop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=crop_image; break; } if (LocaleCompare((const char *) tag,"cycle-colormap") == 0) { ssize_t display; /* Cycle-colormap image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } display=0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"display") == 0) { display=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) CycleColormapImage(msl_info->image[n],display,exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'D': case 'd': { if (LocaleCompare((const char *) tag,"despeckle") == 0) { Image *despeckle_image; /* Despeckle image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } despeckle_image=DespeckleImage(msl_info->image[n], msl_info->exception); if (despeckle_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=despeckle_image; break; } if (LocaleCompare((const char *) tag,"display") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) DisplayImages(msl_info->image_info[n],msl_info->image[n], msl_info->exception); break; } if (LocaleCompare((const char *) tag,"draw") == 0) { char text[MagickPathExtent]; /* Annotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"points") == 0) { if (LocaleCompare(draw_info->primitive,"path") == 0) { (void) ConcatenateString(&draw_info->primitive," '"); ConcatenateString(&draw_info->primitive,value); (void) ConcatenateString(&draw_info->primitive,"'"); } else { (void) ConcatenateString(&draw_info->primitive," "); ConcatenateString(&draw_info->primitive,value); } break; } if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"primitive") == 0) { CloneString(&draw_info->primitive,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->stroke,exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { (void) ConcatenateString(&draw_info->primitive," '"); (void) ConcatenateString(&draw_info->primitive,value); (void) ConcatenateString(&draw_info->primitive,"'"); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->undercolor,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; (void) DrawImage(msl_info->image[n],draw_info,exception); draw_info=DestroyDrawInfo(draw_info); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'E': case 'e': { if (LocaleCompare((const char *) tag,"edge") == 0) { Image *edge_image; /* Edge image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } edge_image=EdgeImage(msl_info->image[n],geometry_info.rho, msl_info->exception); if (edge_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=edge_image; break; } if (LocaleCompare((const char *) tag,"emboss") == 0) { Image *emboss_image; /* Emboss image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } emboss_image=EmbossImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); if (emboss_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=emboss_image; break; } if (LocaleCompare((const char *) tag,"enhance") == 0) { Image *enhance_image; /* Enhance image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } enhance_image=EnhanceImage(msl_info->image[n], msl_info->exception); if (enhance_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=enhance_image; break; } if (LocaleCompare((const char *) tag,"equalize") == 0) { /* Equalize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) EqualizeImage(msl_info->image[n], msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'F': case 'f': { if (LocaleCompare((const char *) tag, "flatten") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* no attributes here */ /* process the image */ { Image *newImage; newImage=MergeImageLayers(msl_info->image[n],FlattenLayer, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } if (LocaleCompare((const char *) tag,"flip") == 0) { Image *flip_image; /* Flip image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } flip_image=FlipImage(msl_info->image[n], msl_info->exception); if (flip_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=flip_image; break; } if (LocaleCompare((const char *) tag,"flop") == 0) { Image *flop_image; /* Flop image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } flop_image=FlopImage(msl_info->image[n], msl_info->exception); if (flop_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=flop_image; break; } if (LocaleCompare((const char *) tag,"frame") == 0) { FrameInfo frame_info; Image *frame_image; /* Frame image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } (void) ResetMagickMemory(&frame_info,0,sizeof(frame_info)); SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"compose") == 0) { option=ParseCommandOption(MagickComposeOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedComposeType", value); msl_info->image[n]->compose=(CompositeOperator) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &msl_info->image[n]->matte_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; frame_info.width=geometry.width; frame_info.height=geometry.height; frame_info.outer_bevel=geometry.x; frame_info.inner_bevel=geometry.y; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { frame_info.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"inner") == 0) { frame_info.inner_bevel=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"outer") == 0) { frame_info.outer_bevel=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { frame_info.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } frame_info.x=(ssize_t) frame_info.width; frame_info.y=(ssize_t) frame_info.height; frame_info.width=msl_info->image[n]->columns+2*frame_info.x; frame_info.height=msl_info->image[n]->rows+2*frame_info.y; frame_image=FrameImage(msl_info->image[n],&frame_info, msl_info->image[n]->compose,msl_info->exception); if (frame_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=frame_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'G': case 'g': { if (LocaleCompare((const char *) tag,"gamma") == 0) { char gamma[MagickPathExtent]; PixelInfo pixel; /* Gamma image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } channel=UndefinedChannel; pixel.red=0.0; pixel.green=0.0; pixel.blue=0.0; *gamma='\0'; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blue") == 0) { pixel.blue=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { (void) CopyMagickString(gamma,value,MagickPathExtent); break; } if (LocaleCompare(keyword,"green") == 0) { pixel.green=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"red") == 0) { pixel.red=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } if (*gamma == '\0') (void) FormatLocaleString(gamma,MagickPathExtent,"%g,%g,%g", (double) pixel.red,(double) pixel.green,(double) pixel.blue); (void) GammaImage(msl_info->image[n],strtod(gamma,(char **) NULL), msl_info->exception); break; } else if (LocaleCompare((const char *) tag,"get") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,(const char *) attributes[i]); (void) CopyMagickString(key,value,MagickPathExtent); switch (*keyword) { case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { (void) FormatLocaleString(value,MagickPathExtent,"%.20g", (double) msl_info->image[n]->rows); (void) SetImageProperty(msl_info->attributes[n],key,value, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { (void) FormatLocaleString(value,MagickPathExtent,"%.20g", (double) msl_info->image[n]->columns); (void) SetImageProperty(msl_info->attributes[n],key,value, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } else if (LocaleCompare((const char *) tag, "group") == 0) { msl_info->number_groups++; msl_info->group_info=(MSLGroupInfo *) ResizeQuantumMemory( msl_info->group_info,msl_info->number_groups+1UL, sizeof(*msl_info->group_info)); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'I': case 'i': { if (LocaleCompare((const char *) tag,"image") == 0) { MSLPushImage(msl_info,(Image *) NULL); if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"color") == 0) { Image *next_image; (void) CopyMagickString(msl_info->image_info[n]->filename, "xc:",MagickPathExtent); (void) ConcatenateMagickString(msl_info->image_info[n]-> filename,value,MagickPathExtent); next_image=ReadImage(msl_info->image_info[n],exception); CatchException(exception); if (next_image == (Image *) NULL) continue; if (msl_info->image[n] == (Image *) NULL) msl_info->image[n]=next_image; else { register Image *p; /* Link image into image list. */ p=msl_info->image[n]; while (p->next != (Image *) NULL) p=GetNextImageInList(p); next_image->previous=p; p->next=next_image; } break; } (void) SetMSLAttributes(msl_info,keyword,value); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } break; } if (LocaleCompare((const char *) tag,"implode") == 0) { Image *implode_image; /* Implode image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"amount") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } implode_image=ImplodeImage(msl_info->image[n],geometry_info.rho, msl_info->image[n]->interpolate,msl_info->exception); if (implode_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=implode_image; break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'L': case 'l': { if (LocaleCompare((const char *) tag,"label") == 0) break; if (LocaleCompare((const char *) tag, "level") == 0) { double levelBlack = 0, levelGamma = 1, levelWhite = QuantumRange; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; CloneString(&value,(const char *) attributes[i]); (void) CopyMagickString(key,value,MagickPathExtent); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"black") == 0) { levelBlack = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gamma") == 0) { levelGamma = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"white") == 0) { levelWhite = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image */ LevelImage(msl_info->image[n],levelBlack,levelWhite,levelGamma, msl_info->exception); break; } } case 'M': case 'm': { if (LocaleCompare((const char *) tag,"magnify") == 0) { Image *magnify_image; /* Magnify image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } magnify_image=MagnifyImage(msl_info->image[n], msl_info->exception); if (magnify_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=magnify_image; break; } if (LocaleCompare((const char *) tag,"map") == 0) { Image *affinity_image; MagickBooleanType dither; QuantizeInfo *quantize_info; /* Map image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } affinity_image=NewImageList(); dither=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"dither") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); dither=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { affinity_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } quantize_info=AcquireQuantizeInfo(msl_info->image_info[n]); quantize_info->dither_method=dither != MagickFalse ? RiemersmaDitherMethod : NoDitherMethod; (void) RemapImages(quantize_info,msl_info->image[n], affinity_image,exception); quantize_info=DestroyQuantizeInfo(quantize_info); affinity_image=DestroyImage(affinity_image); break; } if (LocaleCompare((const char *) tag,"matte-floodfill") == 0) { double opacity; PixelInfo target; PaintMethod paint_method; /* Matte floodfill image. */ opacity=0.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); paint_method=FloodfillMethod; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"bordercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &target,exception); paint_method=FillToBorderMethod; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { opacity=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); (void) GetOneVirtualPixelInfo(msl_info->image[n], TileVirtualPixelMethod,geometry.x,geometry.y,&target, exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); draw_info->fill.alpha=ClampToQuantum(opacity); channel_mask=SetImageChannelMask(msl_info->image[n],AlphaChannel); (void) FloodfillPaintImage(msl_info->image[n],draw_info,&target, geometry.x,geometry.y,paint_method == FloodfillMethod ? MagickFalse : MagickTrue,msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); draw_info=DestroyDrawInfo(draw_info); break; } if (LocaleCompare((const char *) tag,"median-filter") == 0) { Image *median_image; /* Median-filter image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } median_image=StatisticImage(msl_info->image[n],MedianStatistic, (size_t) geometry_info.rho,(size_t) geometry_info.sigma, msl_info->exception); if (median_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=median_image; break; } if (LocaleCompare((const char *) tag,"minify") == 0) { Image *minify_image; /* Minify image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } minify_image=MinifyImage(msl_info->image[n], msl_info->exception); if (minify_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=minify_image; break; } if (LocaleCompare((const char *) tag,"msl") == 0 ) break; if (LocaleCompare((const char *) tag,"modulate") == 0) { char modulate[MagickPathExtent]; /* Modulate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=100.0; geometry_info.sigma=100.0; geometry_info.xi=100.0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'B': case 'b': { if (LocaleCompare(keyword,"blackness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"brightness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"factor") == 0) { flags=ParseGeometry(value,&geometry_info); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"hue") == 0) { geometry_info.xi=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'L': case 'l': { if (LocaleCompare(keyword,"lightness") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"saturation") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"whiteness") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(modulate,MagickPathExtent,"%g,%g,%g", geometry_info.rho,geometry_info.sigma,geometry_info.xi); (void) ModulateImage(msl_info->image[n],modulate, msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'N': case 'n': { if (LocaleCompare((const char *) tag,"negate") == 0) { MagickBooleanType gray; /* Negate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } gray=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"gray") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); gray=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); (void) NegateImage(msl_info->image[n],gray, msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); break; } if (LocaleCompare((const char *) tag,"normalize") == 0) { /* Normalize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) NormalizeImage(msl_info->image[n], msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'O': case 'o': { if (LocaleCompare((const char *) tag,"oil-paint") == 0) { Image *paint_image; /* Oil-paint image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } paint_image=OilPaintImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); if (paint_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=paint_image; break; } if (LocaleCompare((const char *) tag,"opaque") == 0) { PixelInfo fill_color, target; /* Opaque image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } (void) QueryColorCompliance("none",AllCompliance,&target, exception); (void) QueryColorCompliance("none",AllCompliance,&fill_color, exception); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"channel") == 0) { option=ParseChannelOption(value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedChannelType", value); channel=(ChannelType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword,"fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &fill_color,exception); break; } if (LocaleCompare(keyword,"fuzz") == 0) { msl_info->image[n]->fuzz=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } channel_mask=SetImageChannelMask(msl_info->image[n],channel); (void) OpaquePaintImage(msl_info->image[n],&target,&fill_color, MagickFalse,msl_info->exception); (void) SetPixelChannelMask(msl_info->image[n],channel_mask); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'P': case 'p': { if (LocaleCompare((const char *) tag,"print") == 0) { if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'O': case 'o': { if (LocaleCompare(keyword,"output") == 0) { (void) FormatLocaleFile(stdout,"%s",value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } if (LocaleCompare((const char *) tag, "profile") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { const char *name; const StringInfo *profile; Image *profile_image; ImageInfo *profile_info; keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); if (*keyword == '!') { /* Remove a profile from the image. */ (void) ProfileImage(msl_info->image[n],keyword, (const unsigned char *) NULL,0,exception); continue; } /* Associate a profile with the image. */ profile_info=CloneImageInfo(msl_info->image_info[n]); profile=GetImageProfile(msl_info->image[n],"iptc"); if (profile != (StringInfo *) NULL) profile_info->profile=(void *) CloneStringInfo(profile); profile_image=GetImageCache(profile_info,keyword,exception); profile_info=DestroyImageInfo(profile_info); if (profile_image == (Image *) NULL) { char name[MagickPathExtent], filename[MagickPathExtent]; register char *p; StringInfo *profile; (void) CopyMagickString(filename,keyword,MagickPathExtent); (void) CopyMagickString(name,keyword,MagickPathExtent); for (p=filename; *p != '\0'; p++) if ((*p == ':') && (IsPathDirectory(keyword) < 0) && (IsPathAccessible(keyword) == MagickFalse)) { register char *q; /* Look for profile name (e.g. name:profile). */ (void) CopyMagickString(name,filename,(size_t) (p-filename+1)); for (q=filename; *q != '\0'; q++) *q=(*++p); break; } profile=FileToStringInfo(filename,~0UL,exception); if (profile != (StringInfo *) NULL) { (void) ProfileImage(msl_info->image[n],name, GetStringInfoDatum(profile),(size_t) GetStringInfoLength(profile),exception); profile=DestroyStringInfo(profile); } continue; } ResetImageProfileIterator(profile_image); name=GetNextImageProfile(profile_image); while (name != (const char *) NULL) { profile=GetImageProfile(profile_image,name); if (profile != (StringInfo *) NULL) (void) ProfileImage(msl_info->image[n],name, GetStringInfoDatum(profile),(size_t) GetStringInfoLength(profile),exception); name=GetNextImageProfile(profile_image); } profile_image=DestroyImage(profile_image); } break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'Q': case 'q': { if (LocaleCompare((const char *) tag,"quantize") == 0) { QuantizeInfo quantize_info; /* Quantize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } GetQuantizeInfo(&quantize_info); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"colors") == 0) { quantize_info.number_colors=StringToLong(value); break; } if (LocaleCompare(keyword,"colorspace") == 0) { option=ParseCommandOption(MagickColorspaceOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError, "UnrecognizedColorspaceType",value); quantize_info.colorspace=(ColorspaceType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"dither") == 0) { option=ParseCommandOption(MagickDitherOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); quantize_info.dither_method=(DitherMethod) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'M': case 'm': { if (LocaleCompare(keyword,"measure") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); quantize_info.measure_error=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"treedepth") == 0) { quantize_info.tree_depth=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) QuantizeImage(&quantize_info,msl_info->image[n],exception); break; } if (LocaleCompare((const char *) tag,"query-font-metrics") == 0) { char text[MagickPathExtent]; MagickBooleanType status; TypeMetric metrics; /* Query font metrics. */ draw_info=CloneDrawInfo(msl_info->image_info[n], msl_info->draw_info[n]); angle=0.0; current=draw_info->affine; GetAffineMatrix(&affine); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"affine") == 0) { char *p; p=value; draw_info->affine.sx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.rx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ry=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.sy=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.tx=StringToDouble(p,&p); if (*p ==',') p++; draw_info->affine.ty=StringToDouble(p,&p); break; } if (LocaleCompare(keyword,"align") == 0) { option=ParseCommandOption(MagickAlignOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedAlignType", value); draw_info->align=(AlignType) option; break; } if (LocaleCompare(keyword,"antialias") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedBooleanType", value); draw_info->stroke_antialias=(MagickBooleanType) option; draw_info->text_antialias=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { CloneString(&draw_info->density,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"encoding") == 0) { CloneString(&draw_info->encoding,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->fill,exception); break; } if (LocaleCompare(keyword,"family") == 0) { CloneString(&draw_info->family,value); break; } if (LocaleCompare(keyword,"font") == 0) { CloneString(&draw_info->font,value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } if (LocaleCompare(keyword,"gravity") == 0) { option=ParseCommandOption(MagickGravityOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedGravityType", value); draw_info->gravity=(GravityType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'P': case 'p': { if (LocaleCompare(keyword,"pointsize") == 0) { draw_info->pointsize=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"rotate") == 0) { angle=StringToDouble(value,(char **) NULL); affine.sx=cos(DegreesToRadians(fmod(angle,360.0))); affine.rx=sin(DegreesToRadians(fmod(angle,360.0))); affine.ry=(-sin(DegreesToRadians(fmod(angle,360.0)))); affine.sy=cos(DegreesToRadians(fmod(angle,360.0))); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"scale") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.sx=geometry_info.rho; affine.sy=geometry_info.sigma; break; } if (LocaleCompare(keyword,"skewX") == 0) { angle=StringToDouble(value,(char **) NULL); affine.ry=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"skewY") == 0) { angle=StringToDouble(value,(char **) NULL); affine.rx=cos(DegreesToRadians(fmod(angle,360.0))); break; } if (LocaleCompare(keyword,"stretch") == 0) { option=ParseCommandOption(MagickStretchOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStretchType", value); draw_info->stretch=(StretchType) option; break; } if (LocaleCompare(keyword, "stroke") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->stroke,exception); break; } if (LocaleCompare(keyword,"strokewidth") == 0) { draw_info->stroke_width=StringToLong(value); break; } if (LocaleCompare(keyword,"style") == 0) { option=ParseCommandOption(MagickStyleOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedStyleType", value); draw_info->style=(StyleType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"text") == 0) { CloneString(&draw_info->text,value); break; } if (LocaleCompare(keyword,"translate") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; affine.tx=geometry_info.rho; affine.ty=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'U': case 'u': { if (LocaleCompare(keyword, "undercolor") == 0) { (void) QueryColorCompliance(value,AllCompliance, &draw_info->undercolor,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"weight") == 0) { draw_info->weight=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) FormatLocaleString(text,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); CloneString(&draw_info->geometry,text); draw_info->affine.sx=affine.sx*current.sx+affine.ry*current.rx; draw_info->affine.rx=affine.rx*current.sx+affine.sy*current.rx; draw_info->affine.ry=affine.sx*current.ry+affine.ry*current.sy; draw_info->affine.sy=affine.rx*current.ry+affine.sy*current.sy; draw_info->affine.tx=affine.sx*current.tx+affine.ry*current.ty+ affine.tx; draw_info->affine.ty=affine.rx*current.tx+affine.sy*current.ty+ affine.ty; status=GetTypeMetrics(msl_info->attributes[n],draw_info,&metrics, msl_info->exception); if (status != MagickFalse) { Image *image; image=msl_info->attributes[n]; FormatImageProperty(image,"msl:font-metrics.pixels_per_em.x", "%g",metrics.pixels_per_em.x); FormatImageProperty(image,"msl:font-metrics.pixels_per_em.y", "%g",metrics.pixels_per_em.y); FormatImageProperty(image,"msl:font-metrics.ascent","%g", metrics.ascent); FormatImageProperty(image,"msl:font-metrics.descent","%g", metrics.descent); FormatImageProperty(image,"msl:font-metrics.width","%g", metrics.width); FormatImageProperty(image,"msl:font-metrics.height","%g", metrics.height); FormatImageProperty(image,"msl:font-metrics.max_advance","%g", metrics.max_advance); FormatImageProperty(image,"msl:font-metrics.bounds.x1","%g", metrics.bounds.x1); FormatImageProperty(image,"msl:font-metrics.bounds.y1","%g", metrics.bounds.y1); FormatImageProperty(image,"msl:font-metrics.bounds.x2","%g", metrics.bounds.x2); FormatImageProperty(image,"msl:font-metrics.bounds.y2","%g", metrics.bounds.y2); FormatImageProperty(image,"msl:font-metrics.origin.x","%g", metrics.origin.x); FormatImageProperty(image,"msl:font-metrics.origin.y","%g", metrics.origin.y); } draw_info=DestroyDrawInfo(draw_info); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'R': case 'r': { if (LocaleCompare((const char *) tag,"raise") == 0) { MagickBooleanType raise; /* Raise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } raise=MagickFalse; SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"raise") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); raise=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) RaiseImage(msl_info->image[n],&geometry,raise, msl_info->exception); break; } if (LocaleCompare((const char *) tag,"read") == 0) { if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filename") == 0) { Image *image; if (value == (char *) NULL) break; (void) CopyMagickString(msl_info->image_info[n]->filename, value,MagickPathExtent); image=ReadImage(msl_info->image_info[n],exception); CatchException(exception); if (image == (Image *) NULL) continue; AppendImageToList(&msl_info->image[n],image); break; } (void) SetMSLAttributes(msl_info,keyword,value); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } break; } if (LocaleCompare((const char *) tag,"reduce-noise") == 0) { Image *paint_image; /* Reduce-noise image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } paint_image=StatisticImage(msl_info->image[n],NonpeakStatistic, (size_t) geometry_info.rho,(size_t) geometry_info.sigma, msl_info->exception); if (paint_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=paint_image; break; } else if (LocaleCompare((const char *) tag,"repage") == 0) { /* init the values */ width=msl_info->image[n]->page.width; height=msl_info->image[n]->page.height; x=msl_info->image[n]->page.x; y=msl_info->image[n]->page.y; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { int flags; RectangleInfo geometry; flags=ParseAbsoluteGeometry(value,&geometry); if ((flags & WidthValue) != 0) { if ((flags & HeightValue) == 0) geometry.height=geometry.width; width=geometry.width; height=geometry.height; } if ((flags & AspectValue) != 0) { if ((flags & XValue) != 0) x+=geometry.x; if ((flags & YValue) != 0) y+=geometry.y; } else { if ((flags & XValue) != 0) { x=geometry.x; if ((width == 0) && (geometry.x > 0)) width=msl_info->image[n]->columns+geometry.x; } if ((flags & YValue) != 0) { y=geometry.y; if ((height == 0) && (geometry.y > 0)) height=msl_info->image[n]->rows+geometry.y; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { height = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { width = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { x = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { y = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } msl_info->image[n]->page.width=width; msl_info->image[n]->page.height=height; msl_info->image[n]->page.x=x; msl_info->image[n]->page.y=y; break; } else if (LocaleCompare((const char *) tag,"resample") == 0) { double x_resolution, y_resolution; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; x_resolution=DefaultResolution; y_resolution=DefaultResolution; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { ssize_t flags; flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma*=geometry_info.rho; x_resolution=geometry_info.rho; y_resolution=geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x-resolution") == 0) { x_resolution=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y-resolution") == 0) { y_resolution=StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* Resample image. */ { double factor; Image *resample_image; factor=1.0; if (msl_info->image[n]->units == PixelsPerCentimeterResolution) factor=2.54; width=(size_t) (x_resolution*msl_info->image[n]->columns/ (factor*(msl_info->image[n]->resolution.x == 0.0 ? DefaultResolution : msl_info->image[n]->resolution.x))+0.5); height=(size_t) (y_resolution*msl_info->image[n]->rows/ (factor*(msl_info->image[n]->resolution.y == 0.0 ? DefaultResolution : msl_info->image[n]->resolution.y))+0.5); resample_image=ResizeImage(msl_info->image[n],width,height, msl_info->image[n]->filter,msl_info->exception); if (resample_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=resample_image; } break; } if (LocaleCompare((const char *) tag,"resize") == 0) { FilterType filter; Image *resize_image; /* Resize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } filter=UndefinedFilter; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filter") == 0) { option=ParseCommandOption(MagickFilterOptions,MagickFalse, value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); filter=(FilterType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } resize_image=ResizeImage(msl_info->image[n],geometry.width, geometry.height,filter,msl_info->exception); if (resize_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=resize_image; break; } if (LocaleCompare((const char *) tag,"roll") == 0) { Image *roll_image; /* Roll image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } SetGeometry(msl_info->image[n],&geometry); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParsePageGeometry(msl_info->image[n],value, &geometry,exception); if ((flags & HeightValue) == 0) geometry.height=geometry.width; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry.x=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry.y=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } roll_image=RollImage(msl_info->image[n],geometry.x,geometry.y, msl_info->exception); if (roll_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=roll_image; break; } else if (LocaleCompare((const char *) tag,"roll") == 0) { /* init the values */ width=msl_info->image[n]->columns; height=msl_info->image[n]->rows; x = y = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { (void) ParseMetaGeometry(value,&x,&y,&width,&height); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { x = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { y = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; newImage=RollImage(msl_info->image[n], x, y, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } if (LocaleCompare((const char *) tag,"rotate") == 0) { Image *rotate_image; /* Rotate image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } rotate_image=RotateImage(msl_info->image[n],geometry_info.rho, msl_info->exception); if (rotate_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=rotate_image; break; } else if (LocaleCompare((const char *) tag,"rotate") == 0) { /* init the values */ double degrees = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { degrees = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; newImage=RotateImage(msl_info->image[n], degrees, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'S': case 's': { if (LocaleCompare((const char *) tag,"sample") == 0) { Image *sample_image; /* Sample image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } sample_image=SampleImage(msl_info->image[n],geometry.width, geometry.height,msl_info->exception); if (sample_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=sample_image; break; } if (LocaleCompare((const char *) tag,"scale") == 0) { Image *scale_image; /* Scale image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseRegionGeometry(msl_info->image[n],value, &geometry,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { geometry.height=StringToUnsignedLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { geometry.width=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } scale_image=ScaleImage(msl_info->image[n],geometry.width, geometry.height,msl_info->exception); if (scale_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=scale_image; break; } if (LocaleCompare((const char *) tag,"segment") == 0) { ColorspaceType colorspace; MagickBooleanType verbose; /* Segment image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=1.0; geometry_info.sigma=1.5; colorspace=sRGBColorspace; verbose=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"cluster-threshold") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } if (LocaleCompare(keyword,"colorspace") == 0) { option=ParseCommandOption(MagickColorspaceOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError, "UnrecognizedColorspaceType",value); colorspace=(ColorspaceType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.5; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"smoothing-threshold") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SegmentImage(msl_info->image[n],colorspace,verbose, geometry_info.rho,geometry_info.sigma,exception); break; } else if (LocaleCompare((const char *) tag, "set") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"clip-mask") == 0) { for (j=0; j < msl_info->n; j++) { const char *property; property=GetImageProperty(msl_info->attributes[j],"id", exception); if (LocaleCompare(property,value) == 0) { SetImageMask(msl_info->image[n],ReadPixelMask, msl_info->image[j],exception); break; } } break; } if (LocaleCompare(keyword,"clip-path") == 0) { for (j=0; j < msl_info->n; j++) { const char *property; property=GetImageProperty(msl_info->attributes[j],"id", exception); if (LocaleCompare(property,value) == 0) { SetImageMask(msl_info->image[n],ReadPixelMask, msl_info->image[j],exception); break; } } break; } if (LocaleCompare(keyword,"colorspace") == 0) { ssize_t colorspace; colorspace=(ColorspaceType) ParseCommandOption( MagickColorspaceOptions,MagickFalse,value); if (colorspace < 0) ThrowMSLException(OptionError,"UnrecognizedColorspace", value); (void) TransformImageColorspace(msl_info->image[n], (ColorspaceType) colorspace,exception); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, exception); break; } case 'D': case 'd': { if (LocaleCompare(keyword,"density") == 0) { flags=ParseGeometry(value,&geometry_info); msl_info->image[n]->resolution.x=geometry_info.rho; msl_info->image[n]->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) msl_info->image[n]->resolution.y= msl_info->image[n]->resolution.x; break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, exception); break; } case 'O': case 'o': { if (LocaleCompare(keyword, "opacity") == 0) { ssize_t opac = OpaqueAlpha, len = (ssize_t) strlen( value ); if (value[len-1] == '%') { char tmp[100]; (void) CopyMagickString(tmp,value,len); opac = StringToLong( tmp ); opac = (int)(QuantumRange * ((float)opac/100)); } else opac = StringToLong( value ); (void) SetImageAlpha( msl_info->image[n], (Quantum) opac, exception); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, msl_info->exception); break; } case 'P': case 'p': { if (LocaleCompare(keyword, "page") == 0) { char page[MagickPathExtent]; const char *image_option; MagickStatusType flags; RectangleInfo geometry; (void) ResetMagickMemory(&geometry,0,sizeof(geometry)); image_option=GetImageArtifact(msl_info->image[n],"page"); if (image_option != (const char *) NULL) flags=ParseAbsoluteGeometry(image_option,&geometry); flags=ParseAbsoluteGeometry(value,&geometry); (void) FormatLocaleString(page,MagickPathExtent,"%.20gx%.20g", (double) geometry.width,(double) geometry.height); if (((flags & XValue) != 0) || ((flags & YValue) != 0)) (void) FormatLocaleString(page,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) geometry.width, (double) geometry.height,(double) geometry.x,(double) geometry.y); (void) SetImageOption(msl_info->image_info[n],keyword,page); msl_info->image_info[n]->page=GetPageGeometry(page); break; } (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, msl_info->exception); break; } default: { (void) SetMSLAttributes(msl_info,keyword,value); (void) SetImageProperty(msl_info->image[n],keyword,value, msl_info->exception); break; } } } break; } if (LocaleCompare((const char *) tag,"shade") == 0) { Image *shade_image; MagickBooleanType gray; /* Shade image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } gray=MagickFalse; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'A': case 'a': { if (LocaleCompare(keyword,"azimuth") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'E': case 'e': { if (LocaleCompare(keyword,"elevation") == 0) { geometry_info.sigma=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } if (LocaleCompare(keyword,"gray") == 0) { option=ParseCommandOption(MagickBooleanOptions, MagickFalse,value); if (option < 0) ThrowMSLException(OptionError,"UnrecognizedNoiseType", value); gray=(MagickBooleanType) option; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shade_image=ShadeImage(msl_info->image[n],gray,geometry_info.rho, geometry_info.sigma,msl_info->exception); if (shade_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shade_image; break; } if (LocaleCompare((const char *) tag,"shadow") == 0) { Image *shadow_image; /* Shear image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'O': case 'o': { if (LocaleCompare(keyword,"opacity") == 0) { geometry_info.rho=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { geometry_info.sigma=StringToLong(value); break; } break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry_info.xi=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry_info.psi=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shadow_image=ShadowImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,(ssize_t) ceil(geometry_info.xi-0.5), (ssize_t) ceil(geometry_info.psi-0.5),msl_info->exception); if (shadow_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shadow_image; break; } if (LocaleCompare((const char *) tag,"sharpen") == 0) { double radius = 0.0, sigma = 1.0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } /* NOTE: sharpen can have no attributes, since we use all the defaults! */ if (attributes != (const xmlChar **) NULL) { for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'R': case 'r': { if (LocaleCompare(keyword, "radius") == 0) { radius = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'S': case 's': { if (LocaleCompare(keyword,"sigma") == 0) { sigma = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } } /* sharpen image. */ { Image *newImage; newImage=SharpenImage(msl_info->image[n],radius,sigma, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } else if (LocaleCompare((const char *) tag,"shave") == 0) { /* init the values */ width = height = 0; x = y = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { (void) ParseMetaGeometry(value,&x,&y,&width,&height); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'H': case 'h': { if (LocaleCompare(keyword,"height") == 0) { height = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } case 'W': case 'w': { if (LocaleCompare(keyword,"width") == 0) { width = StringToLong( value ); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { Image *newImage; RectangleInfo rectInfo; rectInfo.height = height; rectInfo.width = width; rectInfo.x = x; rectInfo.y = y; newImage=ShaveImage(msl_info->image[n], &rectInfo, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; } break; } if (LocaleCompare((const char *) tag,"shear") == 0) { Image *shear_image; /* Shear image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword, "fill") == 0) { (void) QueryColorCompliance(value,AllCompliance, &msl_info->image[n]->background_color,exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'X': case 'x': { if (LocaleCompare(keyword,"x") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'Y': case 'y': { if (LocaleCompare(keyword,"y") == 0) { geometry_info.sigma=StringToLong(value); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } shear_image=ShearImage(msl_info->image[n],geometry_info.rho, geometry_info.sigma,msl_info->exception); if (shear_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=shear_image; break; } if (LocaleCompare((const char *) tag,"signature") == 0) { /* Signature image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SignatureImage(msl_info->image[n],exception); break; } if (LocaleCompare((const char *) tag,"solarize") == 0) { /* Solarize image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } geometry_info.rho=QuantumRange/2.0; if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'T': case 't': { if (LocaleCompare(keyword,"threshold") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SolarizeImage(msl_info->image[n],geometry_info.rho, msl_info->exception); break; } if (LocaleCompare((const char *) tag,"spread") == 0) { Image *spread_image; /* Spread image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'R': case 'r': { if (LocaleCompare(keyword,"radius") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } spread_image=SpreadImage(msl_info->image[n], msl_info->image[n]->interpolate,geometry_info.rho, msl_info->exception); if (spread_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=spread_image; break; } else if (LocaleCompare((const char *) tag,"stegano") == 0) { Image * watermark = (Image*) NULL; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) { for (j=0; j<msl_info->n;j++) { const char * theAttr = GetImageProperty(msl_info->attributes[j], "id", exception); if (theAttr && LocaleCompare(theAttr, value) == 0) { watermark = msl_info->image[j]; break; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ if ( watermark != (Image*) NULL ) { Image *newImage; newImage=SteganoImage(msl_info->image[n], watermark, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } else ThrowMSLException(OptionError,"MissingWatermarkImage",keyword); } else if (LocaleCompare((const char *) tag,"stereo") == 0) { Image * stereoImage = (Image*) NULL; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) { for (j=0; j<msl_info->n;j++) { const char * theAttr = GetImageProperty(msl_info->attributes[j], "id", exception); if (theAttr && LocaleCompare(theAttr, value) == 0) { stereoImage = msl_info->image[j]; break; } } break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ if ( stereoImage != (Image*) NULL ) { Image *newImage; newImage=StereoImage(msl_info->image[n], stereoImage, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } else ThrowMSLException(OptionError,"Missing stereo image",keyword); } if (LocaleCompare((const char *) tag,"strip") == 0) { /* Strip image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); } (void) StripImage(msl_info->image[n],msl_info->exception); break; } if (LocaleCompare((const char *) tag,"swap") == 0) { Image *p, *q, *swap; ssize_t index, swap_index; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } index=(-1); swap_index=(-2); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'G': case 'g': { if (LocaleCompare(keyword,"indexes") == 0) { flags=ParseGeometry(value,&geometry_info); index=(ssize_t) geometry_info.rho; if ((flags & SigmaValue) == 0) swap_index=(ssize_t) geometry_info.sigma; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } /* Swap images. */ p=GetImageFromList(msl_info->image[n],index); q=GetImageFromList(msl_info->image[n],swap_index); if ((p == (Image *) NULL) || (q == (Image *) NULL)) { ThrowMSLException(OptionError,"NoSuchImage",(const char *) tag); break; } swap=CloneImage(p,0,0,MagickTrue,msl_info->exception); ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue, msl_info->exception)); ReplaceImageInList(&q,swap); msl_info->image[n]=GetFirstImageInList(q); break; } if (LocaleCompare((const char *) tag,"swirl") == 0) { Image *swirl_image; /* Swirl image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'D': case 'd': { if (LocaleCompare(keyword,"degrees") == 0) { geometry_info.rho=StringToDouble(value, (char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } case 'G': case 'g': { if (LocaleCompare(keyword,"geometry") == 0) { flags=ParseGeometry(value,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=1.0; break; } ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } swirl_image=SwirlImage(msl_info->image[n],geometry_info.rho, msl_info->image[n]->interpolate,msl_info->exception); if (swirl_image == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=swirl_image; break; } if (LocaleCompare((const char *) tag,"sync") == 0) { /* Sync image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) SyncImage(msl_info->image[n],exception); break; } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'T': case 't': { if (LocaleCompare((const char *) tag,"map") == 0) { Image *texture_image; /* Texture image. */ if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } texture_image=NewImageList(); if (attributes != (const xmlChar **) NULL) for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i], exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'I': case 'i': { if (LocaleCompare(keyword,"image") == 0) for (j=0; j < msl_info->n; j++) { const char *attribute; attribute=GetImageProperty(msl_info->attributes[j],"id", exception); if ((attribute != (const char *) NULL) && (LocaleCompare(attribute,value) == 0)) { texture_image=CloneImage(msl_info->image[j],0,0, MagickFalse,exception); break; } } break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute", keyword); break; } } } (void) TextureImage(msl_info->image[n],texture_image,exception); texture_image=DestroyImage(texture_image); break; } else if (LocaleCompare((const char *) tag,"threshold") == 0) { /* init the values */ double threshold = 0; if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'T': case 't': { if (LocaleCompare(keyword,"threshold") == 0) { threshold = StringToDouble(value,(char **) NULL); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } /* process image. */ { BilevelImage(msl_info->image[n],threshold,exception); break; } } else if (LocaleCompare((const char *) tag, "transparent") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'C': case 'c': { if (LocaleCompare(keyword,"color") == 0) { PixelInfo target; (void) QueryColorCompliance(value,AllCompliance,&target, exception); (void) TransparentPaintImage(msl_info->image[n],&target, TransparentAlpha,MagickFalse,msl_info->exception); break; } ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } default: { ThrowMSLException(OptionError,"UnrecognizedAttribute",keyword); break; } } } break; } else if (LocaleCompare((const char *) tag, "trim") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined",(const char *) tag); break; } /* no attributes here */ /* process the image */ { Image *newImage; RectangleInfo rectInfo; /* all zeros on a crop == trim edges! */ rectInfo.height = rectInfo.width = 0; rectInfo.x = rectInfo.y = 0; newImage=CropImage(msl_info->image[n],&rectInfo, msl_info->exception); if (newImage == (Image *) NULL) break; msl_info->image[n]=DestroyImage(msl_info->image[n]); msl_info->image[n]=newImage; break; } } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } case 'W': case 'w': { if (LocaleCompare((const char *) tag,"write") == 0) { if (msl_info->image[n] == (Image *) NULL) { ThrowMSLException(OptionError,"NoImagesDefined", (const char *) tag); break; } if (attributes == (const xmlChar **) NULL) break; for (i=0; (attributes[i] != (const xmlChar *) NULL); i++) { keyword=(const char *) attributes[i++]; attribute=InterpretImageProperties(msl_info->image_info[n], msl_info->attributes[n],(const char *) attributes[i],exception); CloneString(&value,attribute); attribute=DestroyString(attribute); switch (*keyword) { case 'F': case 'f': { if (LocaleCompare(keyword,"filename") == 0) { (void) CopyMagickString(msl_info->image[n]->filename,value, MagickPathExtent); break; } (void) SetMSLAttributes(msl_info,keyword,value); } default: { (void) SetMSLAttributes(msl_info,keyword,value); break; } } } /* process */ { *msl_info->image_info[n]->magick='\0'; (void) WriteImage(msl_info->image_info[n], msl_info->image[n], msl_info->exception); break; } } ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); } default: { ThrowMSLException(OptionError,"UnrecognizedElement",(const char *) tag); break; } } if (value != (char *) NULL) value=DestroyString(value); (void) DestroyExceptionInfo(exception); (void) LogMagickEvent(CoderEvent,GetMagickModule()," )"); }
0
udev
662c3110803bd8c1aedacc36788e6fd028944314
CVE-2009-1186
CWE-120
size_t util_path_encode(char *s, size_t len) { char t[(len * 3)+1]; size_t i, j; for (i = 0, j = 0; s[i] != '\0'; i++) { if (s[i] == '/') { memcpy(&t[j], "\\x2f", 4); j += 4; } else if (s[i] == '\\') { memcpy(&t[j], "\\x5c", 4); j += 4; } else { t[j] = s[i]; j++; } } if (len == 0) return j; i = (j < len - 1) ? j : len - 1; memcpy(s, t, i); s[i] = '\0'; return j; }
1
linux-2.6
f2455eb176ac87081bbfc9a44b21c7cd2bc1967e
NOT_APPLICABLE
NOT_APPLICABLE
indicate_pkt( struct net_device *dev ) { struct net_local *nl = (struct net_local *) dev->priv; struct sk_buff *skb = nl->rx_buf_p; skb_put( skb, nl->inppos ); #ifdef CONFIG_SBNI_MULTILINE skb->protocol = eth_type_trans( skb, nl->master ); netif_rx( skb ); dev->last_rx = jiffies; ++((struct net_local *) nl->master->priv)->stats.rx_packets; ((struct net_local *) nl->master->priv)->stats.rx_bytes += nl->inppos; #else skb->protocol = eth_type_trans( skb, dev ); netif_rx( skb ); dev->last_rx = jiffies; ++nl->stats.rx_packets; nl->stats.rx_bytes += nl->inppos; #endif nl->rx_buf_p = NULL; /* protocol driver will clear this sk_buff */ }
0
linux
51093254bf879bc9ce96590400a87897c7498463
NOT_APPLICABLE
NOT_APPLICABLE
static int srpt_map_sg_to_ib_sge(struct srpt_rdma_ch *ch, struct srpt_send_ioctx *ioctx) { struct ib_device *dev = ch->sport->sdev->device; struct se_cmd *cmd; struct scatterlist *sg, *sg_orig; int sg_cnt; enum dma_data_direction dir; struct ib_rdma_wr *riu; struct srp_direct_buf *db; dma_addr_t dma_addr; struct ib_sge *sge; u64 raddr; u32 rsize; u32 tsize; u32 dma_len; int count, nrdma; int i, j, k; BUG_ON(!ch); BUG_ON(!ioctx); cmd = &ioctx->cmd; dir = cmd->data_direction; BUG_ON(dir == DMA_NONE); ioctx->sg = sg = sg_orig = cmd->t_data_sg; ioctx->sg_cnt = sg_cnt = cmd->t_data_nents; count = ib_dma_map_sg(ch->sport->sdev->device, sg, sg_cnt, opposite_dma_dir(dir)); if (unlikely(!count)) return -EAGAIN; ioctx->mapped_sg_count = count; if (ioctx->rdma_wrs && ioctx->n_rdma_wrs) nrdma = ioctx->n_rdma_wrs; else { nrdma = (count + SRPT_DEF_SG_PER_WQE - 1) / SRPT_DEF_SG_PER_WQE + ioctx->n_rbuf; ioctx->rdma_wrs = kcalloc(nrdma, sizeof(*ioctx->rdma_wrs), GFP_KERNEL); if (!ioctx->rdma_wrs) goto free_mem; ioctx->n_rdma_wrs = nrdma; } db = ioctx->rbufs; tsize = cmd->data_length; dma_len = ib_sg_dma_len(dev, &sg[0]); riu = ioctx->rdma_wrs; /* * For each remote desc - calculate the #ib_sge. * If #ib_sge < SRPT_DEF_SG_PER_WQE per rdma operation then * each remote desc rdma_iu is required a rdma wr; * else * we need to allocate extra rdma_iu to carry extra #ib_sge in * another rdma wr */ for (i = 0, j = 0; j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) { rsize = be32_to_cpu(db->len); raddr = be64_to_cpu(db->va); riu->remote_addr = raddr; riu->rkey = be32_to_cpu(db->key); riu->wr.num_sge = 0; /* calculate how many sge required for this remote_buf */ while (rsize > 0 && tsize > 0) { if (rsize >= dma_len) { tsize -= dma_len; rsize -= dma_len; raddr += dma_len; if (tsize > 0) { ++j; if (j < count) { sg = sg_next(sg); dma_len = ib_sg_dma_len( dev, sg); } } } else { tsize -= rsize; dma_len -= rsize; rsize = 0; } ++riu->wr.num_sge; if (rsize > 0 && riu->wr.num_sge == SRPT_DEF_SG_PER_WQE) { ++ioctx->n_rdma; riu->wr.sg_list = kmalloc_array(riu->wr.num_sge, sizeof(*riu->wr.sg_list), GFP_KERNEL); if (!riu->wr.sg_list) goto free_mem; ++riu; riu->wr.num_sge = 0; riu->remote_addr = raddr; riu->rkey = be32_to_cpu(db->key); } } ++ioctx->n_rdma; riu->wr.sg_list = kmalloc_array(riu->wr.num_sge, sizeof(*riu->wr.sg_list), GFP_KERNEL); if (!riu->wr.sg_list) goto free_mem; } db = ioctx->rbufs; tsize = cmd->data_length; riu = ioctx->rdma_wrs; sg = sg_orig; dma_len = ib_sg_dma_len(dev, &sg[0]); dma_addr = ib_sg_dma_address(dev, &sg[0]); /* this second loop is really mapped sg_addres to rdma_iu->ib_sge */ for (i = 0, j = 0; j < count && i < ioctx->n_rbuf && tsize > 0; ++i, ++riu, ++db) { rsize = be32_to_cpu(db->len); sge = riu->wr.sg_list; k = 0; while (rsize > 0 && tsize > 0) { sge->addr = dma_addr; sge->lkey = ch->sport->sdev->pd->local_dma_lkey; if (rsize >= dma_len) { sge->length = (tsize < dma_len) ? tsize : dma_len; tsize -= dma_len; rsize -= dma_len; if (tsize > 0) { ++j; if (j < count) { sg = sg_next(sg); dma_len = ib_sg_dma_len( dev, sg); dma_addr = ib_sg_dma_address( dev, sg); } } } else { sge->length = (tsize < rsize) ? tsize : rsize; tsize -= rsize; dma_len -= rsize; dma_addr += rsize; rsize = 0; } ++k; if (k == riu->wr.num_sge && rsize > 0 && tsize > 0) { ++riu; sge = riu->wr.sg_list; k = 0; } else if (rsize > 0 && tsize > 0) ++sge; } } return 0; free_mem: srpt_unmap_sg_to_ib_sge(ch, ioctx); return -ENOMEM; }
0
jansson
8f80c2d83808150724d31793e6ade92749b1faa4
NOT_APPLICABLE
NOT_APPLICABLE
int json_array_clear(json_t *json) { json_array_t *array; size_t i; if(!json_is_array(json)) return -1; array = json_to_array(json); for(i = 0; i < array->entries; i++) json_decref(array->table[i]); array->entries = 0; return 0; }
0
tensorflow
237822b59fc504dda2c564787f5d3ad9c4aa62d9
NOT_APPLICABLE
NOT_APPLICABLE
bool ParseStringValue(const string& key, PyObject* py_value, TF_Status* status, tensorflow::StringPiece* value) { if (PyBytes_Check(py_value)) { Py_ssize_t size = 0; char* buf = nullptr; if (PyBytes_AsStringAndSize(py_value, &buf, &size) < 0) return false; *value = tensorflow::StringPiece(buf, size); return true; } #if PY_MAJOR_VERSION >= 3 if (PyUnicode_Check(py_value)) { Py_ssize_t size = 0; const char* buf = PyUnicode_AsUTF8AndSize(py_value, &size); if (buf == nullptr) return false; *value = tensorflow::StringPiece(buf, size); return true; } #endif TF_SetStatus( status, TF_INVALID_ARGUMENT, tensorflow::strings::StrCat("Expecting a string value for attr ", key, ", got ", py_value->ob_type->tp_name) .c_str()); return false; }
0
linux
321027c1fe77f892f4ea07846aeae08cefbbb290
NOT_APPLICABLE
NOT_APPLICABLE
perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags) { struct perf_event_context *ctx; retry: /* * One of the few rules of preemptible RCU is that one cannot do * rcu_read_unlock() while holding a scheduler (or nested) lock when * part of the read side critical section was irqs-enabled -- see * rcu_read_unlock_special(). * * Since ctx->lock nests under rq->lock we must ensure the entire read * side critical section has interrupts disabled. */ local_irq_save(*flags); rcu_read_lock(); ctx = rcu_dereference(task->perf_event_ctxp[ctxn]); if (ctx) { /* * If this context is a clone of another, it might * get swapped for another underneath us by * perf_event_task_sched_out, though the * rcu_read_lock() protects us from any context * getting freed. Lock the context and check if it * got swapped before we could get the lock, and retry * if so. If we locked the right context, then it * can't get swapped on us any more. */ raw_spin_lock(&ctx->lock); if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) { raw_spin_unlock(&ctx->lock); rcu_read_unlock(); local_irq_restore(*flags); goto retry; } if (ctx->task == TASK_TOMBSTONE || !atomic_inc_not_zero(&ctx->refcount)) { raw_spin_unlock(&ctx->lock); ctx = NULL; } else { WARN_ON_ONCE(ctx->task != task); } } rcu_read_unlock(); if (!ctx) local_irq_restore(*flags); return ctx; }
0
Chrome
c9d673b54832afde658f214d7da7d0453fa89774
NOT_APPLICABLE
NOT_APPLICABLE
void MemBackendImpl::OnEntryUpdated(MemEntryImpl* entry) { DCHECK(CheckLRUListOrder(lru_list_)); entry->RemoveFromList(); lru_list_.Append(entry); }
0
Android
cc274e2abe8b2a6698a5c47d8aa4bb45f1f9538d
CVE-2016-2464
CWE-20
long long Segment::CreateInstance(IMkvReader* pReader, long long pos, Segment*& pSegment) { assert(pReader); assert(pos >= 0); pSegment = NULL; long long total, available; const long status = pReader->Length(&total, &available); if (status < 0) // error return status; if (available < 0) return -1; if ((total >= 0) && (available > total)) return -1; for (;;) { if ((total >= 0) && (pos >= total)) return E_FILE_FORMAT_INVALID; long len; long long result = GetUIntLength(pReader, pos, len); if (result) // error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; const long long idpos = pos; const long long id = ReadUInt(pReader, pos, len); if (id < 0) // error return id; pos += len; // consume ID result = GetUIntLength(pReader, pos, len); if (result) // error, or too few available bytes return result; if ((total >= 0) && ((pos + len) > total)) return E_FILE_FORMAT_INVALID; if ((pos + len) > available) return pos + len; long long size = ReadUInt(pReader, pos, len); if (size < 0) // error return size; pos += len; // consume length of size of element const long long unknown_size = (1LL << (7 * len)) - 1; if (id == 0x08538067) { // Segment ID if (size == unknown_size) size = -1; else if (total < 0) size = -1; else if ((pos + size) > total) size = -1; pSegment = new (std::nothrow) Segment(pReader, idpos, pos, size); if (pSegment == 0) return -1; // generic error return 0; // success } if (size == unknown_size) return E_FILE_FORMAT_INVALID; if ((total >= 0) && ((pos + size) > total)) return E_FILE_FORMAT_INVALID; if ((pos + size) > available) return pos + size; pos += size; // consume payload } }
1
php
dccda88f27a084bcbbb30198ace12b4e7ae961cc
NOT_APPLICABLE
NOT_APPLICABLE
PHP_FUNCTION(xml_get_current_line_number) { xml_parser *parser; zval *pind; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &pind) == FAILURE) { return; } ZEND_FETCH_RESOURCE(parser,xml_parser *, &pind, -1, "XML Parser", le_xml_parser); RETVAL_LONG(XML_GetCurrentLineNumber(parser->parser)); }
0
linux-2.6
8ed030dd0aa400d18c63861c2c6deb7c38f4edde
NOT_APPLICABLE
NOT_APPLICABLE
int __init ccid_initialize_builtins(void) { int i, err = tfrc_lib_init(); if (err) return err; for (i = 0; i < ARRAY_SIZE(ccids); i++) { err = ccid_activate(ccids[i]); if (err) goto unwind_registrations; } return 0; unwind_registrations: while(--i >= 0) ccid_deactivate(ccids[i]); tfrc_lib_exit(); return err; }
0
Chrome
5576cbc1d3e214dfbb5d3ffcdbe82aa8ba0088fc
NOT_APPLICABLE
NOT_APPLICABLE
MidiManagerUsb::~MidiManagerUsb() { }
0