Dataset Viewer
Auto-converted to Parquet
is_vulnerable
bool
2 classes
func
stringlengths
28
484k
cwe
sequencelengths
1
2
project
stringclasses
592 values
commit_id
stringlengths
7
44
hash
stringlengths
34
39
big_vul_idx
int64
4.09k
189k
idx
int64
0
522k
false
long ssl_get_algorithm2(SSL *s) { long alg2 = s->s3->tmp.new_cipher->algorithm2; if (TLS1_get_version(s) >= TLS1_2_VERSION && alg2 == (SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF)) return SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256; return alg2; }
[ "CWE-310" ]
openssl
ca989269a2876bae79393bd54c3e72d49975fc75
255087747659226932756944884868284698117
177,739
0
true
long ssl_get_algorithm2(SSL *s) { long alg2 = s->s3->tmp.new_cipher->algorithm2; if (s->method->version == TLS1_2_VERSION && alg2 == (SSL_HANDSHAKE_MAC_DEFAULT|TLS1_PRF)) return SSL_HANDSHAKE_MAC_SHA256 | TLS1_PRF_SHA256; return alg2; }
[ "CWE-310" ]
openssl
ca989269a2876bae79393bd54c3e72d49975fc75
185448168336389579295943711163093638128
177,739
157,856
false
gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } *session_data_size = psession.size; if (psession.size > *session_data_size) { ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; }
[ "CWE-119" ]
savannah
190cef6eed37d0e73a73c1e205eb31d45ab60a3c
266005388725654386397960628110885023158
177,741
1
true
gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } if (psession.size > *session_data_size) { ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } *session_data_size = psession.size; if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; }
[ "CWE-119" ]
savannah
190cef6eed37d0e73a73c1e205eb31d45ab60a3c
217937088037221829579003352102231694649
177,741
157,857
false
gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } if (psession.size > *session_data_size) { ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; }
[ "CWE-119" ]
savannah
e82ef4545e9e98cbcb032f55d7c750b81e3a0450
162619476999663411812822607346255778028
177,742
2
true
gnutls_session_get_data (gnutls_session_t session, void *session_data, size_t * session_data_size) { gnutls_datum_t psession; int ret; if (session->internals.resumable == RESUME_FALSE) return GNUTLS_E_INVALID_SESSION; psession.data = session_data; ret = _gnutls_session_pack (session, &psession); if (ret < 0) { gnutls_assert (); return ret; } if (psession.size > *session_data_size) { *session_data_size = psession.size; ret = GNUTLS_E_SHORT_MEMORY_BUFFER; goto error; } if (session_data != NULL) memcpy (session_data, psession.data, psession.size); ret = 0; error: _gnutls_free_datum (&psession); return ret; }
[ "CWE-119" ]
savannah
e82ef4545e9e98cbcb032f55d7c750b81e3a0450
282098968981021847575763555214602715866
177,742
157,858
false
getftp (struct url *u, wgint passed_expected_bytes, wgint *qtyread, wgint restval, ccon *con, int count, wgint *last_expected_bytes, FILE *warc_tmp) { int csock, dtsock, local_sock, res; uerr_t err = RETROK; /* appease the compiler */ FILE *fp; char *respline, *tms; const char *user, *passwd, *tmrate; int cmd = con->cmd; bool pasv_mode_open = false; wgint expected_bytes = 0; bool got_expected_bytes = false; bool rest_failed = false; bool rest_failed = false; int flags; wgint rd_size, previous_rd_size = 0; char type_char; bool try_again; bool list_a_used = false; assert (con != NULL); assert (con->target != NULL); /* Debug-check of the sanity of the request by making sure that LIST and RETR are never both requested (since we can handle only one at a time. */ assert (!((cmd & DO_LIST) && (cmd & DO_RETR))); /* Make sure that at least *something* is requested. */ assert ((cmd & (DO_LIST | DO_CWD | DO_RETR | DO_LOGIN)) != 0); *qtyread = restval; user = u->user; passwd = u->passwd; search_netrc (u->host, (const char **)&user, (const char **)&passwd, 1); user = user ? user : (opt.ftp_user ? opt.ftp_user : opt.user); if (!user) user = "anonymous"; passwd = passwd ? passwd : (opt.ftp_passwd ? opt.ftp_passwd : opt.passwd); if (!passwd) passwd = "-wget@"; dtsock = -1; local_sock = -1; con->dltime = 0; if (!(cmd & DO_LOGIN)) csock = con->csock; else /* cmd & DO_LOGIN */ { char *host = con->proxy ? con->proxy->host : u->host; int port = con->proxy ? con->proxy->port : u->port; /* Login to the server: */ /* First: Establish the control connection. */ csock = connect_to_host (host, port); if (csock == E_HOST) return HOSTERR; else if (csock < 0) return (retryable_socket_connect_error (errno) ? CONERROR : CONIMPOSSIBLE); if (cmd & LEAVE_PENDING) con->csock = csock; else con->csock = -1; /* Second: Login with proper USER/PASS sequence. */ logprintf (LOG_VERBOSE, _("Logging in as %s ... "), quotearg_style (escape_quoting_style, user)); if (opt.server_response) logputs (LOG_ALWAYS, "\n"); if (con->proxy) { /* If proxy is in use, log in as username@target-site. */ char *logname = concat_strings (user, "@", u->host, (char *) 0); err = ftp_login (csock, logname, passwd); xfree (logname); } else err = ftp_login (csock, user, passwd); /* FTPRERR, FTPSRVERR, WRITEFAILED, FTPLOGREFUSED, FTPLOGINC */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Error in server greeting.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPLOGREFUSED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("The server refuses login.\n")); fd_close (csock); con->csock = -1; return FTPLOGREFUSED; case FTPLOGINC: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Login incorrect.\n")); fd_close (csock); con->csock = -1; return FTPLOGINC; case FTPOK: if (!opt.server_response) logputs (LOG_VERBOSE, _("Logged in!\n")); break; default: abort (); } /* Third: Get the system type */ if (!opt.server_response) logprintf (LOG_VERBOSE, "==> SYST ... "); err = ftp_syst (csock, &con->rs, &con->rsu); /* FTPRERR */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Server error, can't determine system type.\n")); break; case FTPOK: /* Everything is OK. */ break; default: abort (); } if (!opt.server_response && err != FTPSRVERR) logputs (LOG_VERBOSE, _("done. ")); /* 2013-10-17 Andrea Urbani (matfanjol) According to the system type I choose which list command will be used. If I don't know that system, I will try, the first time of each session, "LIST -a" and "LIST". (see __LIST_A_EXPLANATION__ below) */ switch (con->rs) { case ST_VMS: /* About ST_VMS there is an old note: 2008-01-29 SMS. For a VMS FTP server, where "LIST -a" may not fail, but will never do what is desired here, skip directly to the simple "LIST" command (assumed to be the last one in the list). */ DEBUGP (("\nVMS: I know it and I will use \"LIST\" as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST_A; break; case ST_UNIX: if (con->rsu == UST_MULTINET) { DEBUGP (("\nUNIX MultiNet: I know it and I will use \"LIST\" " "as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST_A; } else if (con->rsu == UST_TYPE_L8) { DEBUGP (("\nUNIX TYPE L8: I know it and I will use \"LIST -a\" " "as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST; } break; default: break; } /* Fourth: Find the initial ftp directory */ if (!opt.server_response) logprintf (LOG_VERBOSE, "==> PWD ... "); err = ftp_pwd (csock, &con->id); /* FTPRERR */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR : /* PWD unsupported -- assume "/". */ xfree (con->id); con->id = xstrdup ("/"); break; case FTPOK: /* Everything is OK. */ break; default: abort (); } #if 0 /* 2004-09-17 SMS. Don't help me out. Please. A reasonably recent VMS FTP server will cope just fine with UNIX file specifications. This code just spoils things. Discarding the device name, for example, is not a wise move. This code was disabled but left in as an example of what not to do. */ /* VMS will report something like "PUB$DEVICE:[INITIAL.FOLDER]". Convert it to "/INITIAL/FOLDER" */ if (con->rs == ST_VMS) { char *path = strchr (con->id, '['); char *pathend = path ? strchr (path + 1, ']') : NULL; if (!path || !pathend) DEBUGP (("Initial VMS directory not in the form [...]!\n")); else { char *idir = con->id; DEBUGP (("Preprocessing the initial VMS directory\n")); DEBUGP ((" old = '%s'\n", con->id)); /* We do the conversion in-place by copying the stuff between [ and ] to the beginning, and changing dots to slashes at the same time. */ *idir++ = '/'; for (++path; path < pathend; path++, idir++) *idir = *path == '.' ? '/' : *path; *idir = '\0'; DEBUGP ((" new = '%s'\n\n", con->id)); } } #endif /* 0 */ if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); /* Fifth: Set the FTP type. */ type_char = ftp_process_type (u->params); if (!opt.server_response) logprintf (LOG_VERBOSE, "==> TYPE %c ... ", type_char); err = ftp_type (csock, type_char); /* FTPRERR, WRITEFAILED, FTPUNKNOWNTYPE */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPUNKNOWNTYPE: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Unknown type `%c', closing control connection.\n"), type_char); fd_close (csock); con->csock = -1; return err; case FTPOK: /* Everything is OK. */ break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* do login */ if (cmd & DO_CWD) { if (!*u->dir) logputs (LOG_VERBOSE, _("==> CWD not needed.\n")); else { const char *targ = NULL; int cwd_count; int cwd_end; int cwd_start; char *target = u->dir; DEBUGP (("changing working directory\n")); /* Change working directory. To change to a non-absolute Unix directory, we need to prepend initial directory (con->id) to it. Absolute directories "just work". A relative directory is one that does not begin with '/' and, on non-Unix OS'es, one that doesn't begin with "[a-z]:". This is not done for OS400, which doesn't use "/"-delimited directories, nor does it support directory hierarchies. "CWD foo" followed by "CWD bar" leaves us in "bar", not in "foo/bar", as would be customary elsewhere. */ /* 2004-09-20 SMS. Why is this wise even on UNIX? It certainly fouls VMS. See below for a more reliable, more universal method. */ /* 2008-04-22 MJC. I'm not crazy about it either. I'm informed it's useful for misconfigured servers that have some dirs in the path with +x but -r, but this method is not RFC-conformant. I understand the need to deal with crappy server configurations, but it's far better to use the canonical method first, and fall back to kludges second. */ if (target[0] != '/' && !(con->rs != ST_UNIX && c_isalpha (target[0]) && target[1] == ':') && (con->rs != ST_OS400) && (con->rs != ST_VMS)) { int idlen = strlen (con->id); char *ntarget, *p; /* Strip trailing slash(es) from con->id. */ while (idlen > 0 && con->id[idlen - 1] == '/') --idlen; p = ntarget = (char *)alloca (idlen + 1 + strlen (u->dir) + 1); memcpy (p, con->id, idlen); p += idlen; *p++ = '/'; strcpy (p, target); DEBUGP (("Prepended initial PWD to relative path:\n")); DEBUGP ((" pwd: '%s'\n old: '%s'\n new: '%s'\n", con->id, target, ntarget)); target = ntarget; } #if 0 /* 2004-09-17 SMS. Don't help me out. Please. A reasonably recent VMS FTP server will cope just fine with UNIX file specifications. This code just spoils things. Discarding the device name, for example, is not a wise move. This code was disabled but left in as an example of what not to do. */ /* If the FTP host runs VMS, we will have to convert the absolute directory path in UNIX notation to absolute directory path in VMS notation as VMS FTP servers do not like UNIX notation of absolute paths. "VMS notation" is [dir.subdir.subsubdir]. */ if (con->rs == ST_VMS) { char *tmpp; char *ntarget = (char *)alloca (strlen (target) + 2); /* We use a converted initial dir, so directories in TARGET will be separated with slashes, something like "/INITIAL/FOLDER/DIR/SUBDIR". Convert that to "[INITIAL.FOLDER.DIR.SUBDIR]". */ strcpy (ntarget, target); assert (*ntarget == '/'); *ntarget = '['; for (tmpp = ntarget + 1; *tmpp; tmpp++) if (*tmpp == '/') *tmpp = '.'; *tmpp++ = ']'; *tmpp = '\0'; DEBUGP (("Changed file name to VMS syntax:\n")); DEBUGP ((" Unix: '%s'\n VMS: '%s'\n", target, ntarget)); target = ntarget; } #endif /* 0 */ /* 2004-09-20 SMS. A relative directory is relative to the initial directory. Thus, what _is_ useful on VMS (and probably elsewhere) is to CWD to the initial directory (ideally, whatever the server reports, _exactly_, NOT badly UNIX-ixed), and then CWD to the (new) relative directory. This should probably be restructured as a function, called once or twice, but I'm lazy enough to take the badly indented loop short-cut for now. */ /* Decide on one pass (absolute) or two (relative). The VMS restriction may be relaxed when the squirrely code above is reformed. */ if ((con->rs == ST_VMS) && (target[0] != '/')) { cwd_start = 0; DEBUGP (("Using two-step CWD for relative path.\n")); } else { /* Go straight to the target. */ cwd_start = 1; } /* At least one VMS FTP server (TCPware V5.6-2) can switch to a UNIX emulation mode when given a UNIX-like directory specification (like "a/b/c"). If allowed to continue this way, LIST interpretation will be confused, because the system type (SYST response) will not be re-checked, and future UNIX-format directory listings (for multiple URLs or "-r") will be horribly misinterpreted. The cheap and nasty work-around is to do a "CWD []" after a UNIX-like directory specification is used. (A single-level directory is harmless.) This puts the TCPware server back into VMS mode, and does no harm on other servers. Unlike the rest of this block, this particular behavior _is_ VMS-specific, so it gets its own VMS test. */ if ((con->rs == ST_VMS) && (strchr( target, '/') != NULL)) { cwd_end = 3; DEBUGP (("Using extra \"CWD []\" step for VMS server.\n")); } else { cwd_end = 2; } /* 2004-09-20 SMS. */ /* Sorry about the deviant indenting. Laziness. */ for (cwd_count = cwd_start; cwd_count < cwd_end; cwd_count++) { switch (cwd_count) { case 0: /* Step one (optional): Go to the initial directory, exactly as reported by the server. */ targ = con->id; break; case 1: /* Step two: Go to the target directory. (Absolute or relative will work now.) */ targ = target; break; case 2: /* Step three (optional): "CWD []" to restore server VMS-ness. */ targ = "[]"; break; default: logprintf (LOG_ALWAYS, _("Logically impossible section reached in getftp()")); logprintf (LOG_ALWAYS, _("cwd_count: %d\ncwd_start: %d\ncwd_end: %d\n"), cwd_count, cwd_start, cwd_end); abort (); } if (!opt.server_response) logprintf (LOG_VERBOSE, "==> CWD (%d) %s ... ", cwd_count, quotearg_style (escape_quoting_style, target)); err = ftp_cwd (csock, targ); /* FTPRERR, WRITEFAILED, FTPNSFOD */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such directory %s.\n\n"), quote (u->dir)); fd_close (csock); con->csock = -1; return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); } /* for */ /* 2004-09-20 SMS. */ } /* else */ } else /* do not CWD */ logputs (LOG_VERBOSE, _("==> CWD not required.\n")); if ((cmd & DO_RETR) && passed_expected_bytes == 0) { if (opt.verbose) { if (!opt.server_response) logprintf (LOG_VERBOSE, "==> SIZE %s ... ", quotearg_style (escape_quoting_style, u->file)); } err = ftp_size (csock, u->file, &expected_bytes); /* FTPRERR */ switch (err) { case FTPRERR: case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPOK: got_expected_bytes = true; /* Everything is OK. */ break; default: abort (); } if (!opt.server_response) { logprintf (LOG_VERBOSE, "%s\n", expected_bytes ? number_to_static_string (expected_bytes) : _("done.\n")); } } if (cmd & DO_RETR && restval > 0 && restval == expected_bytes) { /* Server confirms that file has length restval. We should stop now. Some servers (f.e. NcFTPd) return error when receive REST 0 */ logputs (LOG_VERBOSE, _("File has already been retrieved.\n")); fd_close (csock); con->csock = -1; return RETRFINISHED; } do { try_again = false; /* If anything is to be retrieved, PORT (or PASV) must be sent. */ if (cmd & (DO_LIST | DO_RETR)) { if (opt.ftp_pasv) { ip_address passive_addr; int passive_port; err = ftp_do_pasv (csock, &passive_addr, &passive_port); /* FTPRERR, WRITEFAILED, FTPNOPASV, FTPINVPASV */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPNOPASV: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Cannot initiate PASV transfer.\n")); break; case FTPINVPASV: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Cannot parse PASV response.\n")); break; case FTPOK: break; default: abort (); } /* switch (err) */ if (err==FTPOK) { DEBUGP (("trying to connect to %s port %d\n", print_address (&passive_addr), passive_port)); dtsock = connect_to_ip (&passive_addr, passive_port, NULL); if (dtsock < 0) { int save_errno = errno; fd_close (csock); con->csock = -1; logprintf (LOG_VERBOSE, _("couldn't connect to %s port %d: %s\n"), print_address (&passive_addr), passive_port, strerror (save_errno)); ? CONERROR : CONIMPOSSIBLE); } pasv_mode_open = true; /* Flag to avoid accept port */ if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* err==FTP_OK */ } if (!pasv_mode_open) /* Try to use a port command if PASV failed */ { err = ftp_do_port (csock, &local_sock); /* FTPRERR, WRITEFAILED, bindport (FTPSYSERR), HOSTERR, logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case CONSOCKERR: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno)); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPSYSERR: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Bind error (%s).\n"), strerror (errno)); fd_close (dtsock); return err; case FTPPORTERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Invalid PORT.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } /* port switch */ if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* dtsock == -1 */ } /* cmd & (DO_LIST | DO_RETR) */ /* Restart if needed. */ if (restval && (cmd & DO_RETR)) { if (!opt.server_response) logprintf (LOG_VERBOSE, "==> REST %s ... ", number_to_static_string (restval)); err = ftp_rest (csock, restval); /* FTPRERR, WRITEFAILED, FTPRESTFAIL */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPRESTFAIL: logputs (LOG_VERBOSE, _("\nREST failed, starting from scratch.\n")); rest_failed = true; break; case FTPOK: break; default: abort (); } if (err != FTPRESTFAIL && !opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* restval && cmd & DO_RETR */ if (cmd & DO_RETR) { /* If we're in spider mode, don't really retrieve anything except the directory listing and verify whether the given "file" exists. */ if (opt.spider) { bool exists = false; struct fileinfo *f; uerr_t _res = ftp_get_listing (u, con, &f); /* Set the DO_RETR command flag again, because it gets unset when calling ftp_get_listing() and would otherwise cause an assertion failure earlier on when this function gets repeatedly called (e.g., when recursing). */ con->cmd |= DO_RETR; if (_res == RETROK) { while (f) { if (!strcmp (f->name, u->file)) { exists = true; break; } f = f->next; } if (exists) { logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("File %s exists.\n"), quote (u->file)); } else { logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file %s.\n"), quote (u->file)); } } fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return RETRFINISHED; } if (opt.verbose) { if (!opt.server_response) { if (restval) logputs (LOG_VERBOSE, "\n"); logprintf (LOG_VERBOSE, "==> RETR %s ... ", quotearg_style (escape_quoting_style, u->file)); } } err = ftp_retr (csock, u->file); /* FTPRERR, WRITEFAILED, FTPNSFOD */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file %s.\n\n"), quote (u->file)); fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); if (! got_expected_bytes) expected_bytes = *last_expected_bytes; } /* do retrieve */ if (cmd & DO_LIST) { if (!opt.server_response) logputs (LOG_VERBOSE, "==> LIST ... "); /* As Maciej W. Rozycki ([email protected]) says, `LIST' without arguments is better than `LIST .'; confirmed by RFC959. */ err = ftp_list (csock, NULL, con->st&AVOID_LIST_A, con->st&AVOID_LIST, &list_a_used); /* FTPRERR, WRITEFAILED */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file or directory %s.\n\n"), quote (".")); fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); if (! got_expected_bytes) expected_bytes = *last_expected_bytes; } /* cmd & DO_LIST */ if (!(cmd & (DO_LIST | DO_RETR)) || (opt.spider && !(cmd & DO_LIST))) return RETRFINISHED; /* Some FTP servers return the total length of file after REST command, others just return the remaining size. */ if (passed_expected_bytes && restval && expected_bytes && (expected_bytes == passed_expected_bytes - restval)) { DEBUGP (("Lying FTP server found, adjusting.\n")); expected_bytes = passed_expected_bytes; } /* If no transmission was required, then everything is OK. */ if (!pasv_mode_open) /* we are not using pasive mode so we need to accept */ }
[ "CWE-200" ]
savannah
075d7556964f5a871a73c22ac4b69f5361295099
114753069609161113628525870463495041364
177,746
3
true
getftp (struct url *u, wgint passed_expected_bytes, wgint *qtyread, wgint restval, ccon *con, int count, wgint *last_expected_bytes, FILE *warc_tmp) { int csock, dtsock, local_sock, res; uerr_t err = RETROK; /* appease the compiler */ FILE *fp; char *respline, *tms; const char *user, *passwd, *tmrate; int cmd = con->cmd; wgint expected_bytes = 0; bool got_expected_bytes = false; bool rest_failed = false; bool rest_failed = false; int flags; wgint rd_size, previous_rd_size = 0; char type_char; bool try_again; bool list_a_used = false; assert (con != NULL); assert (con->target != NULL); /* Debug-check of the sanity of the request by making sure that LIST and RETR are never both requested (since we can handle only one at a time. */ assert (!((cmd & DO_LIST) && (cmd & DO_RETR))); /* Make sure that at least *something* is requested. */ assert ((cmd & (DO_LIST | DO_CWD | DO_RETR | DO_LOGIN)) != 0); *qtyread = restval; user = u->user; passwd = u->passwd; search_netrc (u->host, (const char **)&user, (const char **)&passwd, 1); user = user ? user : (opt.ftp_user ? opt.ftp_user : opt.user); if (!user) user = "anonymous"; passwd = passwd ? passwd : (opt.ftp_passwd ? opt.ftp_passwd : opt.passwd); if (!passwd) passwd = "-wget@"; dtsock = -1; local_sock = -1; con->dltime = 0; if (!(cmd & DO_LOGIN)) csock = con->csock; else /* cmd & DO_LOGIN */ { char *host = con->proxy ? con->proxy->host : u->host; int port = con->proxy ? con->proxy->port : u->port; /* Login to the server: */ /* First: Establish the control connection. */ csock = connect_to_host (host, port); if (csock == E_HOST) return HOSTERR; else if (csock < 0) return (retryable_socket_connect_error (errno) ? CONERROR : CONIMPOSSIBLE); if (cmd & LEAVE_PENDING) con->csock = csock; else con->csock = -1; /* Second: Login with proper USER/PASS sequence. */ logprintf (LOG_VERBOSE, _("Logging in as %s ... "), quotearg_style (escape_quoting_style, user)); if (opt.server_response) logputs (LOG_ALWAYS, "\n"); if (con->proxy) { /* If proxy is in use, log in as username@target-site. */ char *logname = concat_strings (user, "@", u->host, (char *) 0); err = ftp_login (csock, logname, passwd); xfree (logname); } else err = ftp_login (csock, user, passwd); /* FTPRERR, FTPSRVERR, WRITEFAILED, FTPLOGREFUSED, FTPLOGINC */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Error in server greeting.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPLOGREFUSED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("The server refuses login.\n")); fd_close (csock); con->csock = -1; return FTPLOGREFUSED; case FTPLOGINC: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Login incorrect.\n")); fd_close (csock); con->csock = -1; return FTPLOGINC; case FTPOK: if (!opt.server_response) logputs (LOG_VERBOSE, _("Logged in!\n")); break; default: abort (); } /* Third: Get the system type */ if (!opt.server_response) logprintf (LOG_VERBOSE, "==> SYST ... "); err = ftp_syst (csock, &con->rs, &con->rsu); /* FTPRERR */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Server error, can't determine system type.\n")); break; case FTPOK: /* Everything is OK. */ break; default: abort (); } if (!opt.server_response && err != FTPSRVERR) logputs (LOG_VERBOSE, _("done. ")); /* 2013-10-17 Andrea Urbani (matfanjol) According to the system type I choose which list command will be used. If I don't know that system, I will try, the first time of each session, "LIST -a" and "LIST". (see __LIST_A_EXPLANATION__ below) */ switch (con->rs) { case ST_VMS: /* About ST_VMS there is an old note: 2008-01-29 SMS. For a VMS FTP server, where "LIST -a" may not fail, but will never do what is desired here, skip directly to the simple "LIST" command (assumed to be the last one in the list). */ DEBUGP (("\nVMS: I know it and I will use \"LIST\" as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST_A; break; case ST_UNIX: if (con->rsu == UST_MULTINET) { DEBUGP (("\nUNIX MultiNet: I know it and I will use \"LIST\" " "as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST_A; } else if (con->rsu == UST_TYPE_L8) { DEBUGP (("\nUNIX TYPE L8: I know it and I will use \"LIST -a\" " "as standard list command\n")); con->st |= LIST_AFTER_LIST_A_CHECK_DONE; con->st |= AVOID_LIST; } break; default: break; } /* Fourth: Find the initial ftp directory */ if (!opt.server_response) logprintf (LOG_VERBOSE, "==> PWD ... "); err = ftp_pwd (csock, &con->id); /* FTPRERR */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPSRVERR : /* PWD unsupported -- assume "/". */ xfree (con->id); con->id = xstrdup ("/"); break; case FTPOK: /* Everything is OK. */ break; default: abort (); } #if 0 /* 2004-09-17 SMS. Don't help me out. Please. A reasonably recent VMS FTP server will cope just fine with UNIX file specifications. This code just spoils things. Discarding the device name, for example, is not a wise move. This code was disabled but left in as an example of what not to do. */ /* VMS will report something like "PUB$DEVICE:[INITIAL.FOLDER]". Convert it to "/INITIAL/FOLDER" */ if (con->rs == ST_VMS) { char *path = strchr (con->id, '['); char *pathend = path ? strchr (path + 1, ']') : NULL; if (!path || !pathend) DEBUGP (("Initial VMS directory not in the form [...]!\n")); else { char *idir = con->id; DEBUGP (("Preprocessing the initial VMS directory\n")); DEBUGP ((" old = '%s'\n", con->id)); /* We do the conversion in-place by copying the stuff between [ and ] to the beginning, and changing dots to slashes at the same time. */ *idir++ = '/'; for (++path; path < pathend; path++, idir++) *idir = *path == '.' ? '/' : *path; *idir = '\0'; DEBUGP ((" new = '%s'\n\n", con->id)); } } #endif /* 0 */ if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); /* Fifth: Set the FTP type. */ type_char = ftp_process_type (u->params); if (!opt.server_response) logprintf (LOG_VERBOSE, "==> TYPE %c ... ", type_char); err = ftp_type (csock, type_char); /* FTPRERR, WRITEFAILED, FTPUNKNOWNTYPE */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPUNKNOWNTYPE: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Unknown type `%c', closing control connection.\n"), type_char); fd_close (csock); con->csock = -1; return err; case FTPOK: /* Everything is OK. */ break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* do login */ if (cmd & DO_CWD) { if (!*u->dir) logputs (LOG_VERBOSE, _("==> CWD not needed.\n")); else { const char *targ = NULL; int cwd_count; int cwd_end; int cwd_start; char *target = u->dir; DEBUGP (("changing working directory\n")); /* Change working directory. To change to a non-absolute Unix directory, we need to prepend initial directory (con->id) to it. Absolute directories "just work". A relative directory is one that does not begin with '/' and, on non-Unix OS'es, one that doesn't begin with "[a-z]:". This is not done for OS400, which doesn't use "/"-delimited directories, nor does it support directory hierarchies. "CWD foo" followed by "CWD bar" leaves us in "bar", not in "foo/bar", as would be customary elsewhere. */ /* 2004-09-20 SMS. Why is this wise even on UNIX? It certainly fouls VMS. See below for a more reliable, more universal method. */ /* 2008-04-22 MJC. I'm not crazy about it either. I'm informed it's useful for misconfigured servers that have some dirs in the path with +x but -r, but this method is not RFC-conformant. I understand the need to deal with crappy server configurations, but it's far better to use the canonical method first, and fall back to kludges second. */ if (target[0] != '/' && !(con->rs != ST_UNIX && c_isalpha (target[0]) && target[1] == ':') && (con->rs != ST_OS400) && (con->rs != ST_VMS)) { int idlen = strlen (con->id); char *ntarget, *p; /* Strip trailing slash(es) from con->id. */ while (idlen > 0 && con->id[idlen - 1] == '/') --idlen; p = ntarget = (char *)alloca (idlen + 1 + strlen (u->dir) + 1); memcpy (p, con->id, idlen); p += idlen; *p++ = '/'; strcpy (p, target); DEBUGP (("Prepended initial PWD to relative path:\n")); DEBUGP ((" pwd: '%s'\n old: '%s'\n new: '%s'\n", con->id, target, ntarget)); target = ntarget; } #if 0 /* 2004-09-17 SMS. Don't help me out. Please. A reasonably recent VMS FTP server will cope just fine with UNIX file specifications. This code just spoils things. Discarding the device name, for example, is not a wise move. This code was disabled but left in as an example of what not to do. */ /* If the FTP host runs VMS, we will have to convert the absolute directory path in UNIX notation to absolute directory path in VMS notation as VMS FTP servers do not like UNIX notation of absolute paths. "VMS notation" is [dir.subdir.subsubdir]. */ if (con->rs == ST_VMS) { char *tmpp; char *ntarget = (char *)alloca (strlen (target) + 2); /* We use a converted initial dir, so directories in TARGET will be separated with slashes, something like "/INITIAL/FOLDER/DIR/SUBDIR". Convert that to "[INITIAL.FOLDER.DIR.SUBDIR]". */ strcpy (ntarget, target); assert (*ntarget == '/'); *ntarget = '['; for (tmpp = ntarget + 1; *tmpp; tmpp++) if (*tmpp == '/') *tmpp = '.'; *tmpp++ = ']'; *tmpp = '\0'; DEBUGP (("Changed file name to VMS syntax:\n")); DEBUGP ((" Unix: '%s'\n VMS: '%s'\n", target, ntarget)); target = ntarget; } #endif /* 0 */ /* 2004-09-20 SMS. A relative directory is relative to the initial directory. Thus, what _is_ useful on VMS (and probably elsewhere) is to CWD to the initial directory (ideally, whatever the server reports, _exactly_, NOT badly UNIX-ixed), and then CWD to the (new) relative directory. This should probably be restructured as a function, called once or twice, but I'm lazy enough to take the badly indented loop short-cut for now. */ /* Decide on one pass (absolute) or two (relative). The VMS restriction may be relaxed when the squirrely code above is reformed. */ if ((con->rs == ST_VMS) && (target[0] != '/')) { cwd_start = 0; DEBUGP (("Using two-step CWD for relative path.\n")); } else { /* Go straight to the target. */ cwd_start = 1; } /* At least one VMS FTP server (TCPware V5.6-2) can switch to a UNIX emulation mode when given a UNIX-like directory specification (like "a/b/c"). If allowed to continue this way, LIST interpretation will be confused, because the system type (SYST response) will not be re-checked, and future UNIX-format directory listings (for multiple URLs or "-r") will be horribly misinterpreted. The cheap and nasty work-around is to do a "CWD []" after a UNIX-like directory specification is used. (A single-level directory is harmless.) This puts the TCPware server back into VMS mode, and does no harm on other servers. Unlike the rest of this block, this particular behavior _is_ VMS-specific, so it gets its own VMS test. */ if ((con->rs == ST_VMS) && (strchr( target, '/') != NULL)) { cwd_end = 3; DEBUGP (("Using extra \"CWD []\" step for VMS server.\n")); } else { cwd_end = 2; } /* 2004-09-20 SMS. */ /* Sorry about the deviant indenting. Laziness. */ for (cwd_count = cwd_start; cwd_count < cwd_end; cwd_count++) { switch (cwd_count) { case 0: /* Step one (optional): Go to the initial directory, exactly as reported by the server. */ targ = con->id; break; case 1: /* Step two: Go to the target directory. (Absolute or relative will work now.) */ targ = target; break; case 2: /* Step three (optional): "CWD []" to restore server VMS-ness. */ targ = "[]"; break; default: logprintf (LOG_ALWAYS, _("Logically impossible section reached in getftp()")); logprintf (LOG_ALWAYS, _("cwd_count: %d\ncwd_start: %d\ncwd_end: %d\n"), cwd_count, cwd_start, cwd_end); abort (); } if (!opt.server_response) logprintf (LOG_VERBOSE, "==> CWD (%d) %s ... ", cwd_count, quotearg_style (escape_quoting_style, target)); err = ftp_cwd (csock, targ); /* FTPRERR, WRITEFAILED, FTPNSFOD */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such directory %s.\n\n"), quote (u->dir)); fd_close (csock); con->csock = -1; return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); } /* for */ /* 2004-09-20 SMS. */ } /* else */ } else /* do not CWD */ logputs (LOG_VERBOSE, _("==> CWD not required.\n")); if ((cmd & DO_RETR) && passed_expected_bytes == 0) { if (opt.verbose) { if (!opt.server_response) logprintf (LOG_VERBOSE, "==> SIZE %s ... ", quotearg_style (escape_quoting_style, u->file)); } err = ftp_size (csock, u->file, &expected_bytes); /* FTPRERR */ switch (err) { case FTPRERR: case FTPSRVERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPOK: got_expected_bytes = true; /* Everything is OK. */ break; default: abort (); } if (!opt.server_response) { logprintf (LOG_VERBOSE, "%s\n", expected_bytes ? number_to_static_string (expected_bytes) : _("done.\n")); } } if (cmd & DO_RETR && restval > 0 && restval == expected_bytes) { /* Server confirms that file has length restval. We should stop now. Some servers (f.e. NcFTPd) return error when receive REST 0 */ logputs (LOG_VERBOSE, _("File has already been retrieved.\n")); fd_close (csock); con->csock = -1; return RETRFINISHED; } do { try_again = false; /* If anything is to be retrieved, PORT (or PASV) must be sent. */ if (cmd & (DO_LIST | DO_RETR)) { if (opt.ftp_pasv) { ip_address passive_addr; int passive_port; err = ftp_do_pasv (csock, &passive_addr, &passive_port); /* FTPRERR, WRITEFAILED, FTPNOPASV, FTPINVPASV */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; return err; case FTPNOPASV: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Cannot initiate PASV transfer.\n")); break; case FTPINVPASV: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Cannot parse PASV response.\n")); break; case FTPOK: break; default: abort (); } /* switch (err) */ if (err==FTPOK) { DEBUGP (("trying to connect to %s port %d\n", print_address (&passive_addr), passive_port)); dtsock = connect_to_ip (&passive_addr, passive_port, NULL); if (dtsock < 0) { int save_errno = errno; fd_close (csock); con->csock = -1; logprintf (LOG_VERBOSE, _("couldn't connect to %s port %d: %s\n"), print_address (&passive_addr), passive_port, strerror (save_errno)); ? CONERROR : CONIMPOSSIBLE); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } else return err; /* * We do not want to fall back from PASSIVE mode to ACTIVE mode ! * The reason is the PORT command exposes the client's real IP address * to the server. Bad for someone who relies on privacy via a ftp proxy. */ } else { err = ftp_do_port (csock, &local_sock); /* FTPRERR, WRITEFAILED, bindport (FTPSYSERR), HOSTERR, logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case CONSOCKERR: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, "socket: %s\n", strerror (errno)); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPSYSERR: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("Bind error (%s).\n"), strerror (errno)); fd_close (dtsock); return err; case FTPPORTERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Invalid PORT.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } /* port switch */ if (!opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* dtsock == -1 */ } /* cmd & (DO_LIST | DO_RETR) */ /* Restart if needed. */ if (restval && (cmd & DO_RETR)) { if (!opt.server_response) logprintf (LOG_VERBOSE, "==> REST %s ... ", number_to_static_string (restval)); err = ftp_rest (csock, restval); /* FTPRERR, WRITEFAILED, FTPRESTFAIL */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPRESTFAIL: logputs (LOG_VERBOSE, _("\nREST failed, starting from scratch.\n")); rest_failed = true; break; case FTPOK: break; default: abort (); } if (err != FTPRESTFAIL && !opt.server_response) logputs (LOG_VERBOSE, _("done. ")); } /* restval && cmd & DO_RETR */ if (cmd & DO_RETR) { /* If we're in spider mode, don't really retrieve anything except the directory listing and verify whether the given "file" exists. */ if (opt.spider) { bool exists = false; struct fileinfo *f; uerr_t _res = ftp_get_listing (u, con, &f); /* Set the DO_RETR command flag again, because it gets unset when calling ftp_get_listing() and would otherwise cause an assertion failure earlier on when this function gets repeatedly called (e.g., when recursing). */ con->cmd |= DO_RETR; if (_res == RETROK) { while (f) { if (!strcmp (f->name, u->file)) { exists = true; break; } f = f->next; } if (exists) { logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("File %s exists.\n"), quote (u->file)); } else { logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file %s.\n"), quote (u->file)); } } fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return RETRFINISHED; } if (opt.verbose) { if (!opt.server_response) { if (restval) logputs (LOG_VERBOSE, "\n"); logprintf (LOG_VERBOSE, "==> RETR %s ... ", quotearg_style (escape_quoting_style, u->file)); } } err = ftp_retr (csock, u->file); /* FTPRERR, WRITEFAILED, FTPNSFOD */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file %s.\n\n"), quote (u->file)); fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); if (! got_expected_bytes) expected_bytes = *last_expected_bytes; } /* do retrieve */ if (cmd & DO_LIST) { if (!opt.server_response) logputs (LOG_VERBOSE, "==> LIST ... "); /* As Maciej W. Rozycki ([email protected]) says, `LIST' without arguments is better than `LIST .'; confirmed by RFC959. */ err = ftp_list (csock, NULL, con->st&AVOID_LIST_A, con->st&AVOID_LIST, &list_a_used); /* FTPRERR, WRITEFAILED */ switch (err) { case FTPRERR: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("\ Error in server response, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case WRITEFAILED: logputs (LOG_VERBOSE, "\n"); logputs (LOG_NOTQUIET, _("Write failed, closing control connection.\n")); fd_close (csock); con->csock = -1; fd_close (dtsock); fd_close (local_sock); return err; case FTPNSFOD: logputs (LOG_VERBOSE, "\n"); logprintf (LOG_NOTQUIET, _("No such file or directory %s.\n\n"), quote (".")); fd_close (dtsock); fd_close (local_sock); return err; case FTPOK: break; default: abort (); } if (!opt.server_response) logputs (LOG_VERBOSE, _("done.\n")); if (! got_expected_bytes) expected_bytes = *last_expected_bytes; } /* cmd & DO_LIST */ if (!(cmd & (DO_LIST | DO_RETR)) || (opt.spider && !(cmd & DO_LIST))) return RETRFINISHED; /* Some FTP servers return the total length of file after REST command, others just return the remaining size. */ if (passed_expected_bytes && restval && expected_bytes && (expected_bytes == passed_expected_bytes - restval)) { DEBUGP (("Lying FTP server found, adjusting.\n")); expected_bytes = passed_expected_bytes; } /* If no transmission was required, then everything is OK. */ if (!pasv_mode_open) /* we are not using pasive mode so we need to accept */ }
[ "CWE-200" ]
savannah
075d7556964f5a871a73c22ac4b69f5361295099
230484519226133503077096905290707768008
177,746
157,859
false
add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many) { int current; cmap_splay *tree; if (low > high) { fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name); return; } tree = cmap->tree; if (cmap->tlen) { unsigned int move = cmap->ttop; unsigned int gt = EMPTY; unsigned int lt = EMPTY; if (check_for_overlap) { /* Check for collision with the current node */ do { current = move; /* Cases we might meet: * tree[i]: <-----> * case 0: <-> * case 1: <-------> * case 2: <-------------> * case 3: <-> * case 4: <-------> * case 5: <-> */ if (low <= tree[current].low && tree[current].low <= high) { /* case 1, reduces to case 0 */ /* or case 2, deleting the node */ tree[current].out += high + 1 - tree[current].low; tree[current].low = high + 1; if (tree[current].low > tree[current].high) { move = delete_node(cmap, current); current = EMPTY; continue; } } else if (low <= tree[current].high && tree[current].high <= high) { /* case 4, reduces to case 5 */ tree[current].high = low - 1; assert(tree[current].low <= tree[current].high); } else if (tree[current].low < low && high < tree[current].high) { /* case 3, reduces to case 5 */ int new_high = tree[current].high; tree[current].high = low-1; add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many); } /* Now look for where to move to next (left for case 0, right for case 5) */ if (tree[current].low > high) { gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } else { do { current = move; if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } /* current is now the node to which we would be adding the new node */ /* lt is the last node we traversed which is lt the new node. */ /* gt is the last node we traversed which is gt the new node. */ if (!many) { /* Check for the 'merge' cases. */ if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low) { tree[lt].high = high; if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[lt].high = tree[gt].high; delete_node(cmap, gt); } goto exit; } if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[gt].low = low; tree[gt].out = out; goto exit; } } } else current = EMPTY; if (cmap->tlen == cmap->tcap) { int new_cap = cmap->tcap ? cmap->tcap * 2 : 256; tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree); cmap->tcap = new_cap; } tree[cmap->tlen].low = low; tree[cmap->tlen].high = high; tree[cmap->tlen].out = out; tree[cmap->tlen].parent = current; tree[cmap->tlen].left = EMPTY; tree[cmap->tlen].right = EMPTY; tree[cmap->tlen].many = many; cmap->tlen++; if (current == EMPTY) cmap->ttop = 0; else if (tree[current].low > high) tree[current].left = cmap->tlen-1; else { assert(tree[current].high < low); tree[current].right = cmap->tlen-1; } move_to_root(tree, cmap->tlen-1); cmap->ttop = cmap->tlen-1; exit: {} #ifdef CHECK_SPLAY check_splay(cmap->tree, cmap->ttop, 0); #endif #ifdef DUMP_SPLAY dump_splay(cmap->tree, cmap->ttop, 0, ""); #endif }
[ "CWE-416" ]
ghostscript
f597300439e62f5e921f0d7b1e880b5c1a1f1607
73361849657881456808355395187124534685
177,749
6
true
add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many) { int current; cmap_splay *tree; if (low > high) { fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name); return; } tree = cmap->tree; if (cmap->tlen) { unsigned int move = cmap->ttop; unsigned int gt = EMPTY; unsigned int lt = EMPTY; if (check_for_overlap) { /* Check for collision with the current node */ do { current = move; /* Cases we might meet: * tree[i]: <-----> * case 0: <-> * case 1: <-------> * case 2: <-------------> * case 3: <-> * case 4: <-------> * case 5: <-> */ if (low <= tree[current].low && tree[current].low <= high) { /* case 1, reduces to case 0 */ /* or case 2, deleting the node */ tree[current].out += high + 1 - tree[current].low; tree[current].low = high + 1; if (tree[current].low > tree[current].high) { move = delete_node(cmap, current); current = EMPTY; continue; } } else if (low <= tree[current].high && tree[current].high <= high) { /* case 4, reduces to case 5 */ tree[current].high = low - 1; assert(tree[current].low <= tree[current].high); } else if (tree[current].low < low && high < tree[current].high) { /* case 3, reduces to case 5 */ int new_high = tree[current].high; tree[current].high = low-1; add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many); tree = cmap->tree; } /* Now look for where to move to next (left for case 0, right for case 5) */ if (tree[current].low > high) { gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } else { do { current = move; if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } /* current is now the node to which we would be adding the new node */ /* lt is the last node we traversed which is lt the new node. */ /* gt is the last node we traversed which is gt the new node. */ if (!many) { /* Check for the 'merge' cases. */ if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low) { tree[lt].high = high; if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[lt].high = tree[gt].high; delete_node(cmap, gt); } goto exit; } if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[gt].low = low; tree[gt].out = out; goto exit; } } } else current = EMPTY; if (cmap->tlen == cmap->tcap) { int new_cap = cmap->tcap ? cmap->tcap * 2 : 256; tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree); cmap->tcap = new_cap; } tree[cmap->tlen].low = low; tree[cmap->tlen].high = high; tree[cmap->tlen].out = out; tree[cmap->tlen].parent = current; tree[cmap->tlen].left = EMPTY; tree[cmap->tlen].right = EMPTY; tree[cmap->tlen].many = many; cmap->tlen++; if (current == EMPTY) cmap->ttop = 0; else if (tree[current].low > high) tree[current].left = cmap->tlen-1; else { assert(tree[current].high < low); tree[current].right = cmap->tlen-1; } move_to_root(tree, cmap->tlen-1); cmap->ttop = cmap->tlen-1; exit: {} #ifdef CHECK_SPLAY check_splay(cmap->tree, cmap->ttop, 0); #endif #ifdef DUMP_SPLAY dump_splay(cmap->tree, cmap->ttop, 0, ""); #endif }
[ "CWE-416" ]
ghostscript
f597300439e62f5e921f0d7b1e880b5c1a1f1607
124485393887214475174443050553758560429
177,749
157,862
false
add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many) { int current; cmap_splay *tree; if (low > high) { fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name); return; } tree = cmap->tree; if (cmap->tlen) { unsigned int move = cmap->ttop; unsigned int gt = EMPTY; unsigned int lt = EMPTY; if (check_for_overlap) { /* Check for collision with the current node */ do { current = move; /* Cases we might meet: * tree[i]: <-----> * case 0: <-> * case 1: <-------> * case 2: <-------------> * case 3: <-> * case 4: <-------> * case 5: <-> */ if (low <= tree[current].low && tree[current].low <= high) { /* case 1, reduces to case 0 */ /* or case 2, deleting the node */ tree[current].out += high + 1 - tree[current].low; tree[current].low = high + 1; if (tree[current].low > tree[current].high) { move = delete_node(cmap, current); current = EMPTY; continue; } } else if (low <= tree[current].high && tree[current].high <= high) { /* case 4, reduces to case 5 */ tree[current].high = low - 1; assert(tree[current].low <= tree[current].high); } else if (tree[current].low < low && high < tree[current].high) { /* case 3, reduces to case 5 */ int new_high = tree[current].high; tree[current].high = low-1; add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, many); } /* Now look for where to move to next (left for case 0, right for case 5) */ if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } else { do { current = move; if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } /* current is now the node to which we would be adding the new node */ /* lt is the last node we traversed which is lt the new node. */ /* gt is the last node we traversed which is gt the new node. */ if (!many) { /* Check for the 'merge' cases. */ if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low) { tree[lt].high = high; if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[lt].high = tree[gt].high; delete_node(cmap, gt); } goto exit; } if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[gt].low = low; tree[gt].out = out; goto exit; } } } else current = EMPTY; if (cmap->tlen == cmap->tcap) { int new_cap = cmap->tcap ? cmap->tcap * 2 : 256; tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree); cmap->tcap = new_cap; } tree[cmap->tlen].low = low; tree[cmap->tlen].high = high; tree[cmap->tlen].out = out; tree[cmap->tlen].parent = current; tree[cmap->tlen].left = EMPTY; tree[cmap->tlen].right = EMPTY; tree[cmap->tlen].many = many; cmap->tlen++; if (current == EMPTY) cmap->ttop = 0; else if (tree[current].low > high) tree[current].left = cmap->tlen-1; else { assert(tree[current].high < low); tree[current].right = cmap->tlen-1; } move_to_root(tree, cmap->tlen-1); cmap->ttop = cmap->tlen-1; exit: {} #ifdef CHECK_SPLAY check_splay(cmap->tree, cmap->ttop, 0); #endif #ifdef DUMP_SPLAY dump_splay(cmap->tree, cmap->ttop, 0, ""); #endif }
[ "CWE-416" ]
ghostscript
71ceebcf56e682504da22c4035b39a2d451e8ffd
72963719227623516762803191293835350908
177,751
8
true
add_range(fz_context *ctx, pdf_cmap *cmap, unsigned int low, unsigned int high, unsigned int out, int check_for_overlap, int many) { int current; cmap_splay *tree; if (low > high) { fz_warn(ctx, "range limits out of range in cmap %s", cmap->cmap_name); return; } tree = cmap->tree; if (cmap->tlen) { unsigned int move = cmap->ttop; unsigned int gt = EMPTY; unsigned int lt = EMPTY; if (check_for_overlap) { /* Check for collision with the current node */ do { current = move; /* Cases we might meet: * tree[i]: <-----> * case 0: <-> * case 1: <-------> * case 2: <-------------> * case 3: <-> * case 4: <-------> * case 5: <-> */ if (low <= tree[current].low && tree[current].low <= high) { /* case 1, reduces to case 0 */ /* or case 2, deleting the node */ tree[current].out += high + 1 - tree[current].low; tree[current].low = high + 1; if (tree[current].low > tree[current].high) { move = delete_node(cmap, current); current = EMPTY; continue; } } else if (low <= tree[current].high && tree[current].high <= high) { /* case 4, reduces to case 5 */ tree[current].high = low - 1; assert(tree[current].low <= tree[current].high); } else if (tree[current].low < low && high < tree[current].high) { /* case 3, reduces to case 5 */ int new_high = tree[current].high; tree[current].high = low-1; add_range(ctx, cmap, high+1, new_high, tree[current].out + high + 1 - tree[current].low, 0, tree[current].many); } /* Now look for where to move to next (left for case 0, right for case 5) */ if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } else { do { current = move; if (tree[current].low > high) { move = tree[current].left; gt = current; } else { move = tree[current].right; lt = current; } } while (move != EMPTY); } /* current is now the node to which we would be adding the new node */ /* lt is the last node we traversed which is lt the new node. */ /* gt is the last node we traversed which is gt the new node. */ if (!many) { /* Check for the 'merge' cases. */ if (lt != EMPTY && !tree[lt].many && tree[lt].high == low-1 && tree[lt].out - tree[lt].low == out - low) { tree[lt].high = high; if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[lt].high = tree[gt].high; delete_node(cmap, gt); } goto exit; } if (gt != EMPTY && !tree[gt].many && tree[gt].low == high+1 && tree[gt].out - tree[gt].low == out - low) { tree[gt].low = low; tree[gt].out = out; goto exit; } } } else current = EMPTY; if (cmap->tlen == cmap->tcap) { int new_cap = cmap->tcap ? cmap->tcap * 2 : 256; tree = cmap->tree = fz_resize_array(ctx, cmap->tree, new_cap, sizeof *cmap->tree); cmap->tcap = new_cap; } tree[cmap->tlen].low = low; tree[cmap->tlen].high = high; tree[cmap->tlen].out = out; tree[cmap->tlen].parent = current; tree[cmap->tlen].left = EMPTY; tree[cmap->tlen].right = EMPTY; tree[cmap->tlen].many = many; cmap->tlen++; if (current == EMPTY) cmap->ttop = 0; else if (tree[current].low > high) tree[current].left = cmap->tlen-1; else { assert(tree[current].high < low); tree[current].right = cmap->tlen-1; } move_to_root(tree, cmap->tlen-1); cmap->ttop = cmap->tlen-1; exit: {} #ifdef CHECK_SPLAY check_splay(cmap->tree, cmap->ttop, 0); #endif #ifdef DUMP_SPLAY dump_splay(cmap->tree, cmap->ttop, 0, ""); #endif }
[ "CWE-416" ]
ghostscript
71ceebcf56e682504da22c4035b39a2d451e8ffd
146583299015225488764454157462983427672
177,751
157,863
false
pdf_show_image(fz_context *ctx, pdf_run_processor *pr, fz_image *image) { pdf_gstate *gstate = pr->gstate + pr->gtop; fz_matrix image_ctm; fz_rect bbox; softmask_save softmask = { NULL }; if (pr->super.hidden) return; break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox); bbox = fz_unit_rect; fz_transform_rect(&bbox, &image_ctm); if (image->mask) { /* apply blend group even though we skip the soft mask */ if (gstate->blendmode) fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1); fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox); } else gstate = pdf_begin_group(ctx, pr, &bbox, &softmask); if (!image->colorspace) { switch (gstate->fill.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_fill_image_mask(ctx, pr->dev, image, &image_ctm, gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params); break; case PDF_MAT_PATTERN: if (gstate->fill.pattern) { fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox); fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params); fz_pop_clip(ctx, pr->dev); } break; } } else { fz_fill_image(ctx, pr->dev, image, &image_ctm, gstate->fill.alpha, &gstate->fill.color_params); } if (image->mask) { fz_pop_clip(ctx, pr->dev); if (gstate->blendmode) fz_end_group(ctx, pr->dev); } else pdf_end_group(ctx, pr, &softmask); } static void if (pr->clip) { gstate->clip_depth++; fz_clip_path(ctx, pr->dev, path, pr->clip_even_odd, &gstate->ctm, &bbox); pr->clip = 0; } if (pr->super.hidden) dostroke = dofill = 0; if (dofill || dostroke) gstate = pdf_begin_group(ctx, pr, &bbox, &softmask); if (dofill && dostroke) { /* We may need to push a knockout group */ if (gstate->stroke.alpha == 0) { /* No need for group, as stroke won't do anything */ } else if (gstate->stroke.alpha == 1.0f && gstate->blendmode == FZ_BLEND_NORMAL) { /* No need for group, as stroke won't show up */ } else { knockout_group = 1; fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 1, FZ_BLEND_NORMAL, 1); } } if (dofill) { switch (gstate->fill.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_fill_path(ctx, pr->dev, path, even_odd, &gstate->ctm, gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params); break; case PDF_MAT_PATTERN: if (gstate->fill.pattern) { fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox); /* The cluster and page 2 of patterns.pdf shows that fz_fill_shade should NOT be called with gstate->ctm. */ fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params); fz_pop_clip(ctx, pr->dev); } break; } } if (dostroke) { switch (gstate->stroke.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, gstate->stroke.colorspace, gstate->stroke.v, gstate->stroke.alpha, &gstate->stroke.color_params); break; case PDF_MAT_PATTERN: if (gstate->stroke.pattern) { fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->stroke.pattern, &pr->gstate[gstate->stroke.gstate_num], &bbox, PDF_STROKE); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->stroke.shade) { fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox); fz_fill_shade(ctx, pr->dev, gstate->stroke.shade, &pr->gstate[gstate->stroke.gstate_num].ctm, gstate->stroke.alpha, &gstate->stroke.color_params); fz_pop_clip(ctx, pr->dev); } break; } } if (knockout_group) fz_end_group(ctx, pr->dev); if (dofill || dostroke) pdf_end_group(ctx, pr, &softmask); }
[ "CWE-20" ]
ghostscript
b2e7d38e845c7d4922d05e6e41f3a2dc1bc1b14a
327424409628836476675717770567987598130
177,752
9
true
pdf_show_image(fz_context *ctx, pdf_run_processor *pr, fz_image *image) { pdf_gstate *gstate = pr->gstate + pr->gtop; fz_matrix image_ctm; fz_rect bbox; if (pr->super.hidden) return; break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_image_mask(ctx, pr->dev, image, &image_ctm, &bbox); bbox = fz_unit_rect; fz_transform_rect(&bbox, &image_ctm); if (image->mask && gstate->blendmode) { /* apply blend group even though we skip the soft mask */ fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 0, gstate->blendmode, 1); fz_try(ctx) fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox); fz_catch(ctx) { fz_end_group(ctx, pr->dev); fz_rethrow(ctx); } fz_try(ctx) pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox); fz_always(ctx) { fz_pop_clip(ctx, pr->dev); fz_end_group(ctx, pr->dev); } fz_catch(ctx) fz_rethrow(ctx); } else if (image->mask) { fz_clip_image_mask(ctx, pr->dev, image->mask, &image_ctm, &bbox); fz_try(ctx) pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox); fz_always(ctx) fz_pop_clip(ctx, pr->dev); fz_catch(ctx) fz_rethrow(ctx); } else { softmask_save softmask = { NULL }; gstate = pdf_begin_group(ctx, pr, &bbox, &softmask); fz_try(ctx) pdf_show_image_imp(ctx, pr, image, &image_ctm, &bbox); fz_always(ctx) pdf_end_group(ctx, pr, &softmask); fz_catch(ctx) fz_rethrow(ctx); } } static void if (pr->clip) { gstate->clip_depth++; fz_clip_path(ctx, pr->dev, path, pr->clip_even_odd, &gstate->ctm, &bbox); pr->clip = 0; } if (pr->super.hidden) dostroke = dofill = 0; if (dofill || dostroke) gstate = pdf_begin_group(ctx, pr, &bbox, &softmask); if (dofill && dostroke) { /* We may need to push a knockout group */ if (gstate->stroke.alpha == 0) { /* No need for group, as stroke won't do anything */ } else if (gstate->stroke.alpha == 1.0f && gstate->blendmode == FZ_BLEND_NORMAL) { /* No need for group, as stroke won't show up */ } else { knockout_group = 1; fz_begin_group(ctx, pr->dev, &bbox, NULL, 0, 1, FZ_BLEND_NORMAL, 1); } } if (dofill) { switch (gstate->fill.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_fill_path(ctx, pr->dev, path, even_odd, &gstate->ctm, gstate->fill.colorspace, gstate->fill.v, gstate->fill.alpha, &gstate->fill.color_params); break; case PDF_MAT_PATTERN: if (gstate->fill.pattern) { fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->fill.pattern, &pr->gstate[gstate->fill.gstate_num], &bbox, PDF_FILL); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->fill.shade) { fz_clip_path(ctx, pr->dev, path, even_odd, &gstate->ctm, &bbox); /* The cluster and page 2 of patterns.pdf shows that fz_fill_shade should NOT be called with gstate->ctm. */ fz_fill_shade(ctx, pr->dev, gstate->fill.shade, &pr->gstate[gstate->fill.gstate_num].ctm, gstate->fill.alpha, &gstate->fill.color_params); fz_pop_clip(ctx, pr->dev); } break; } } if (dostroke) { switch (gstate->stroke.kind) { case PDF_MAT_NONE: break; case PDF_MAT_COLOR: fz_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, gstate->stroke.colorspace, gstate->stroke.v, gstate->stroke.alpha, &gstate->stroke.color_params); break; case PDF_MAT_PATTERN: if (gstate->stroke.pattern) { fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox); pdf_show_pattern(ctx, pr, gstate->stroke.pattern, &pr->gstate[gstate->stroke.gstate_num], &bbox, PDF_STROKE); fz_pop_clip(ctx, pr->dev); } break; case PDF_MAT_SHADE: if (gstate->stroke.shade) { fz_clip_stroke_path(ctx, pr->dev, path, gstate->stroke_state, &gstate->ctm, &bbox); fz_fill_shade(ctx, pr->dev, gstate->stroke.shade, &pr->gstate[gstate->stroke.gstate_num].ctm, gstate->stroke.alpha, &gstate->stroke.color_params); fz_pop_clip(ctx, pr->dev); } break; } } if (knockout_group) fz_end_group(ctx, pr->dev); if (dofill || dostroke) pdf_end_group(ctx, pr, &softmask); }
[ "CWE-20" ]
ghostscript
b2e7d38e845c7d4922d05e6e41f3a2dc1bc1b14a
103996721370606474168467973808469707242
177,752
157,864
false
sparse_dump_region (struct tar_sparse_file *file, size_t i) { union block *blk; off_t bytes_left = file->stat_info->sparse_map[i].numbytes; if (!lseek_or_error (file, file->stat_info->sparse_map[i].offset)) return false; while (bytes_left > 0) { size_t bufsize = (bytes_left > BLOCKSIZE) ? BLOCKSIZE : bytes_left; size_t bytes_read; blk = find_next_block (); bytes_read = safe_read (file->fd, blk->buffer, bufsize); if (bytes_read == SAFE_READ_ERROR) { read_diag_details (file->stat_info->orig_file_name, (file->stat_info->sparse_map[i].offset + file->stat_info->sparse_map[i].numbytes - bytes_left), bufsize); return false; } memset (blk->buffer + bytes_read, 0, BLOCKSIZE - bytes_read); bytes_left -= bytes_read; { size_t count; size_t wrbytes = (write_size > BLOCKSIZE) ? BLOCKSIZE : write_size; union block *blk = find_next_block (); if (!blk) { ERROR ((0, 0, _("Unexpected EOF in archive"))); return false; } set_next_block_after (blk); count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; file->dumped_size += count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) { write_error_details (file->stat_info->orig_file_name, count, wrbytes); return false; } } return true; } /* Interface functions */ enum dump_status sparse_dump_file (int fd, struct tar_stat_info *st) { return false; } set_next_block_after (blk); count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; file->dumped_size += count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) rc = sparse_scan_file (&file); if (rc && file.optab->dump_region) { tar_sparse_dump_header (&file); if (fd >= 0) { size_t i; mv_begin_write (file.stat_info->file_name, file.stat_info->stat.st_size, file.stat_info->archive_file_size - file.dumped_size); for (i = 0; rc && i < file.stat_info->sparse_map_avail; i++) rc = tar_sparse_dump_region (&file, i); } } pad_archive (file.stat_info->archive_file_size - file.dumped_size); return (tar_sparse_done (&file) && rc) ? dump_status_ok : dump_status_short; }
[ "CWE-835" ]
savannah
c15c42ccd1e2377945fd0414eca1a49294bff454
265039722963046446329719176641029797849
177,768
23
true
sparse_dump_region (struct tar_sparse_file *file, size_t i) { union block *blk; off_t bytes_left = file->stat_info->sparse_map[i].numbytes; if (!lseek_or_error (file, file->stat_info->sparse_map[i].offset)) return false; while (bytes_left > 0) { size_t bufsize = (bytes_left > BLOCKSIZE) ? BLOCKSIZE : bytes_left; size_t bytes_read; blk = find_next_block (); bytes_read = safe_read (file->fd, blk->buffer, bufsize); if (bytes_read == SAFE_READ_ERROR) { read_diag_details (file->stat_info->orig_file_name, (file->stat_info->sparse_map[i].offset + file->stat_info->sparse_map[i].numbytes - bytes_left), bufsize); return false; } else if (bytes_read == 0) { char buf[UINTMAX_STRSIZE_BOUND]; struct stat st; size_t n; if (fstat (file->fd, &st) == 0) n = file->stat_info->stat.st_size - st.st_size; else n = file->stat_info->stat.st_size - (file->stat_info->sparse_map[i].offset + file->stat_info->sparse_map[i].numbytes - bytes_left); WARNOPT (WARN_FILE_SHRANK, (0, 0, ngettext ("%s: File shrank by %s byte; padding with zeros", "%s: File shrank by %s bytes; padding with zeros", n), quotearg_colon (file->stat_info->orig_file_name), STRINGIFY_BIGINT (n, buf))); if (! ignore_failed_read_option) set_exit_status (TAREXIT_DIFFERS); return false; } memset (blk->buffer + bytes_read, 0, BLOCKSIZE - bytes_read); bytes_left -= bytes_read; { size_t count; size_t wrbytes = (write_size > BLOCKSIZE) ? BLOCKSIZE : write_size; union block *blk = find_next_block (); if (!blk) { ERROR ((0, 0, _("Unexpected EOF in archive"))); return false; } set_next_block_after (blk); count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; file->dumped_size += count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) { write_error_details (file->stat_info->orig_file_name, count, wrbytes); return false; } } return true; } /* Interface functions */ enum dump_status sparse_dump_file (int fd, struct tar_stat_info *st) { return false; } set_next_block_after (blk); file->dumped_size += BLOCKSIZE; count = blocking_write (file->fd, blk->buffer, wrbytes); write_size -= count; mv_size_left (file->stat_info->archive_file_size - file->dumped_size); file->offset += count; if (count != wrbytes) rc = sparse_scan_file (&file); if (rc && file.optab->dump_region) { tar_sparse_dump_header (&file); if (fd >= 0) { size_t i; mv_begin_write (file.stat_info->file_name, file.stat_info->stat.st_size, file.stat_info->archive_file_size - file.dumped_size); for (i = 0; rc && i < file.stat_info->sparse_map_avail; i++) rc = tar_sparse_dump_region (&file, i); } } pad_archive (file.stat_info->archive_file_size - file.dumped_size); return (tar_sparse_done (&file) && rc) ? dump_status_ok : dump_status_short; }
[ "CWE-835" ]
savannah
c15c42ccd1e2377945fd0414eca1a49294bff454
67919736298016751923724729486340465129
177,768
157,878
false
int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr, char *buf, int *len_ptr) { int len, iflags = 0; struct file_list *flist; uchar fnamecmp_type = FNAMECMP_FNAME; int ndx; read_loop: while (1) { ndx = read_ndx(f_in); if (ndx >= 0) break; if (ndx == NDX_DONE) return ndx; if (ndx == NDX_DEL_STATS) { read_del_stats(f_in); if (am_sender && am_server) write_del_stats(f_out); continue; } if (!inc_recurse || am_sender) { int last; if (first_flist) last = first_flist->prev->ndx_start + first_flist->prev->used - 1; else last = -1; rprintf(FERROR, "Invalid file index: %d (%d - %d) [%s]\n", ndx, NDX_DONE, last, who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (ndx == NDX_FLIST_EOF) { flist_eof = 1; if (DEBUG_GTE(FLIST, 3)) rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i()); write_int(f_out, NDX_FLIST_EOF); continue; } ndx = NDX_FLIST_OFFSET - ndx; if (ndx < 0 || ndx >= dir_flist->used) { ndx = NDX_FLIST_OFFSET - ndx; rprintf(FERROR, "Invalid dir index: %d (%d - %d) [%s]\n", ndx, NDX_FLIST_OFFSET, NDX_FLIST_OFFSET - dir_flist->used + 1, who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (DEBUG_GTE(FLIST, 2)) { rprintf(FINFO, "[%s] receiving flist for dir %d\n", who_am_i(), ndx); } /* Send all the data we read for this flist to the generator. */ start_flist_forward(ndx); flist = recv_file_list(f_in, ndx); flist->parent_ndx = ndx; stop_flist_forward(); } iflags = protocol_version >= 29 ? read_shortint(f_in) : ITEM_TRANSFER | ITEM_MISSING_DATA; /* Support the protocol-29 keep-alive style. */ if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) { if (am_sender) maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH); goto read_loop; } flist = flist_for_ndx(ndx, "read_ndx_and_attrs"); if (flist != cur_flist) { cur_flist = flist; if (am_sender) { file_old_total = cur_flist->used; for (flist = first_flist; flist != cur_flist; flist = flist->next) file_old_total += flist->used; } } if (iflags & ITEM_BASIS_TYPE_FOLLOWS) fnamecmp_type = read_byte(f_in); *type_ptr = fnamecmp_type; if (iflags & ITEM_XNAME_FOLLOWS) { if (iflags & ITEM_XNAME_FOLLOWS) { if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0) exit_cleanup(RERR_PROTOCOL); } else { *buf = '\0'; len = -1; rprintf(FERROR, "received request to transfer non-regular file: %d [%s]\n", ndx, who_am_i()); exit_cleanup(RERR_PROTOCOL); } } *iflag_ptr = iflags; return ndx; }
[ "Other" ]
samba
70aeb5fddd1b2f8e143276f8d5a085db16c593b9
218007185182567162788891557146038450271
177,770
25
true
int read_ndx_and_attrs(int f_in, int f_out, int *iflag_ptr, uchar *type_ptr, char *buf, int *len_ptr) { int len, iflags = 0; struct file_list *flist; uchar fnamecmp_type = FNAMECMP_FNAME; int ndx; read_loop: while (1) { ndx = read_ndx(f_in); if (ndx >= 0) break; if (ndx == NDX_DONE) return ndx; if (ndx == NDX_DEL_STATS) { read_del_stats(f_in); if (am_sender && am_server) write_del_stats(f_out); continue; } if (!inc_recurse || am_sender) { int last; if (first_flist) last = first_flist->prev->ndx_start + first_flist->prev->used - 1; else last = -1; rprintf(FERROR, "Invalid file index: %d (%d - %d) [%s]\n", ndx, NDX_DONE, last, who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (ndx == NDX_FLIST_EOF) { flist_eof = 1; if (DEBUG_GTE(FLIST, 3)) rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i()); write_int(f_out, NDX_FLIST_EOF); continue; } ndx = NDX_FLIST_OFFSET - ndx; if (ndx < 0 || ndx >= dir_flist->used) { ndx = NDX_FLIST_OFFSET - ndx; rprintf(FERROR, "Invalid dir index: %d (%d - %d) [%s]\n", ndx, NDX_FLIST_OFFSET, NDX_FLIST_OFFSET - dir_flist->used + 1, who_am_i()); exit_cleanup(RERR_PROTOCOL); } if (DEBUG_GTE(FLIST, 2)) { rprintf(FINFO, "[%s] receiving flist for dir %d\n", who_am_i(), ndx); } /* Send all the data we read for this flist to the generator. */ start_flist_forward(ndx); flist = recv_file_list(f_in, ndx); flist->parent_ndx = ndx; stop_flist_forward(); } iflags = protocol_version >= 29 ? read_shortint(f_in) : ITEM_TRANSFER | ITEM_MISSING_DATA; /* Support the protocol-29 keep-alive style. */ if (protocol_version < 30 && ndx == cur_flist->used && iflags == ITEM_IS_NEW) { if (am_sender) maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH); goto read_loop; } flist = flist_for_ndx(ndx, "read_ndx_and_attrs"); if (flist != cur_flist) { cur_flist = flist; if (am_sender) { file_old_total = cur_flist->used; for (flist = first_flist; flist != cur_flist; flist = flist->next) file_old_total += flist->used; } } if (iflags & ITEM_BASIS_TYPE_FOLLOWS) fnamecmp_type = read_byte(f_in); *type_ptr = fnamecmp_type; if (iflags & ITEM_XNAME_FOLLOWS) { if (iflags & ITEM_XNAME_FOLLOWS) { if ((len = read_vstring(f_in, buf, MAXPATHLEN)) < 0) exit_cleanup(RERR_PROTOCOL); if (sanitize_paths) { sanitize_path(buf, buf, "", 0, SP_DEFAULT); len = strlen(buf); } } else { *buf = '\0'; len = -1; rprintf(FERROR, "received request to transfer non-regular file: %d [%s]\n", ndx, who_am_i()); exit_cleanup(RERR_PROTOCOL); } } *iflag_ptr = iflags; return ndx; }
[ "Other" ]
samba
70aeb5fddd1b2f8e143276f8d5a085db16c593b9
173509734569313928092432437809749954291
177,770
157,880
false
int dns_read_name(unsigned char *buffer, unsigned char *bufend, unsigned char *name, char *destination, int dest_len, int *offset) { int nb_bytes = 0, n = 0; int label_len; unsigned char *reader = name; char *dest = destination; while (1) { /* Name compression is in use */ if ((*reader & 0xc0) == 0xc0) { /* Must point BEFORE current position */ if ((buffer + reader[1]) > reader) goto err; n = dns_read_name(buffer, bufend, buffer + reader[1], dest, dest_len - nb_bytes, offset); if (n == 0) goto err; } label_len = *reader; if (label_len == 0) goto out; /* Check if: * - we won't read outside the buffer * - there is enough place in the destination */ if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len)) goto err; /* +1 to take label len + label string */ label_len++; memcpy(dest, reader, label_len); dest += label_len; nb_bytes += label_len; reader += label_len; } out: /* offset computation: * parse from <name> until finding either NULL or a pointer "c0xx" */ reader = name; *offset = 0; while (reader < bufend) { if ((reader[0] & 0xc0) == 0xc0) { *offset += 2; break; } else if (*reader == 0) { *offset += 1; break; } *offset += 1; ++reader; } return nb_bytes; err: return 0; }
[ "CWE-835" ]
haproxy
58df5aea0a0c926b2238f65908f5e9f83d1cca25
6381338430754950645676757195002300075
177,771
26
true
int dns_read_name(unsigned char *buffer, unsigned char *bufend, unsigned char *name, char *destination, int dest_len, int *offset, unsigned int depth) { int nb_bytes = 0, n = 0; int label_len; unsigned char *reader = name; char *dest = destination; while (1) { /* Name compression is in use */ if ((*reader & 0xc0) == 0xc0) { /* Must point BEFORE current position */ if ((buffer + reader[1]) > reader) goto err; if (depth++ > 100) goto err; n = dns_read_name(buffer, bufend, buffer + reader[1], dest, dest_len - nb_bytes, offset, depth); if (n == 0) goto err; } label_len = *reader; if (label_len == 0) goto out; /* Check if: * - we won't read outside the buffer * - there is enough place in the destination */ if ((reader + label_len >= bufend) || (nb_bytes + label_len >= dest_len)) goto err; /* +1 to take label len + label string */ label_len++; memcpy(dest, reader, label_len); dest += label_len; nb_bytes += label_len; reader += label_len; } out: /* offset computation: * parse from <name> until finding either NULL or a pointer "c0xx" */ reader = name; *offset = 0; while (reader < bufend) { if ((reader[0] & 0xc0) == 0xc0) { *offset += 2; break; } else if (*reader == 0) { *offset += 1; break; } *offset += 1; ++reader; } return nb_bytes; err: return 0; }
[ "CWE-835" ]
haproxy
58df5aea0a0c926b2238f65908f5e9f83d1cca25
89452639221463286839806233233037284865
177,771
157,881
false
void SplashOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, int *maskColors, GBool inlineImg) { double *ctm; SplashCoord mat[6]; SplashOutImageData imgData; SplashColorMode srcMode; SplashImageSource src; GfxGray gray; GfxRGB rgb; #if SPLASH_CMYK GfxCMYK cmyk; #endif Guchar pix; int n, i; ctm = state->getCTM(); mat[0] = ctm[0]; mat[1] = ctm[1]; mat[2] = -ctm[2]; mat[3] = -ctm[3]; mat[4] = ctm[2] + ctm[4]; mat[5] = ctm[3] + ctm[5]; imgData.imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgData.imgStr->reset(); imgData.colorMap = colorMap; imgData.maskColors = maskColors; imgData.colorMode = colorMode; imgData.width = width; imgData.height = height; imgData.y = 0; imgData.lookup = NULL; if (colorMap->getNumPixelComps() == 1) { n = 1 << colorMap->getBits(); switch (colorMode) { case splashModeMono1: case splashModeMono8: imgData.lookup = (SplashColorPtr)gmalloc(n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getGray(&pix, &gray); imgData.lookup[i] = colToByte(gray); } break; case splashModeRGB8: case splashModeBGR8: imgData.lookup = (SplashColorPtr)gmallocn(n, 3); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getRGB(&pix, &rgb); imgData.lookup[3*i] = colToByte(rgb.r); imgData.lookup[3*i+1] = colToByte(rgb.g); imgData.lookup[3*i+2] = colToByte(rgb.b); } break; case splashModeXBGR8: imgData.lookup = (SplashColorPtr)gmallocn(n, 3); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getRGB(&pix, &rgb); imgData.lookup[4*i] = colToByte(rgb.r); imgData.lookup[4*i+1] = colToByte(rgb.g); imgData.lookup[4*i+2] = colToByte(rgb.b); imgData.lookup[4*i+3] = 255; } break; #if SPLASH_CMYK case splashModeCMYK8: imgData.lookup = (SplashColorPtr)gmallocn(n, 4); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getCMYK(&pix, &cmyk); imgData.lookup[4*i] = colToByte(cmyk.c); imgData.lookup[4*i+1] = colToByte(cmyk.m); imgData.lookup[4*i+2] = colToByte(cmyk.y); imgData.lookup[4*i+3] = colToByte(cmyk.k); } break; #endif break; } } if (colorMode == splashModeMono1) { srcMode = splashModeMono8; } else { srcMode = colorMode; } src = maskColors ? &alphaImageSrc : &imageSrc; splash->drawImage(src, &imgData, srcMode, maskColors ? gTrue : gFalse, width, height, mat); if (inlineImg) { while (imgData.y < height) { imgData.imgStr->getLine(); ++imgData.y; } } gfree(imgData.lookup); delete imgData.imgStr; str->close(); }
[ "CWE-189" ]
poppler
284a92899602daa4a7f429e61849e794569310b5
304076538021281751998637961089745244390
177,774
27
true
void SplashOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, int *maskColors, GBool inlineImg) { double *ctm; SplashCoord mat[6]; SplashOutImageData imgData; SplashColorMode srcMode; SplashImageSource src; GfxGray gray; GfxRGB rgb; #if SPLASH_CMYK GfxCMYK cmyk; #endif Guchar pix; int n, i; ctm = state->getCTM(); mat[0] = ctm[0]; mat[1] = ctm[1]; mat[2] = -ctm[2]; mat[3] = -ctm[3]; mat[4] = ctm[2] + ctm[4]; mat[5] = ctm[3] + ctm[5]; imgData.imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgData.imgStr->reset(); imgData.colorMap = colorMap; imgData.maskColors = maskColors; imgData.colorMode = colorMode; imgData.width = width; imgData.height = height; imgData.y = 0; imgData.lookup = NULL; if (colorMap->getNumPixelComps() == 1) { n = 1 << colorMap->getBits(); switch (colorMode) { case splashModeMono1: case splashModeMono8: imgData.lookup = (SplashColorPtr)gmalloc(n); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getGray(&pix, &gray); imgData.lookup[i] = colToByte(gray); } break; case splashModeRGB8: case splashModeBGR8: imgData.lookup = (SplashColorPtr)gmallocn(n, 3); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getRGB(&pix, &rgb); imgData.lookup[3*i] = colToByte(rgb.r); imgData.lookup[3*i+1] = colToByte(rgb.g); imgData.lookup[3*i+2] = colToByte(rgb.b); } break; case splashModeXBGR8: imgData.lookup = (SplashColorPtr)gmallocn(n, 4); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getRGB(&pix, &rgb); imgData.lookup[4*i] = colToByte(rgb.r); imgData.lookup[4*i+1] = colToByte(rgb.g); imgData.lookup[4*i+2] = colToByte(rgb.b); imgData.lookup[4*i+3] = 255; } break; #if SPLASH_CMYK case splashModeCMYK8: imgData.lookup = (SplashColorPtr)gmallocn(n, 4); for (i = 0; i < n; ++i) { pix = (Guchar)i; colorMap->getCMYK(&pix, &cmyk); imgData.lookup[4*i] = colToByte(cmyk.c); imgData.lookup[4*i+1] = colToByte(cmyk.m); imgData.lookup[4*i+2] = colToByte(cmyk.y); imgData.lookup[4*i+3] = colToByte(cmyk.k); } break; #endif break; } } if (colorMode == splashModeMono1) { srcMode = splashModeMono8; } else { srcMode = colorMode; } src = maskColors ? &alphaImageSrc : &imageSrc; splash->drawImage(src, &imgData, srcMode, maskColors ? gTrue : gFalse, width, height, mat); if (inlineImg) { while (imgData.y < height) { imgData.imgStr->getLine(); ++imgData.y; } } gfree(imgData.lookup); delete imgData.imgStr; str->close(); }
[ "CWE-189" ]
poppler
284a92899602daa4a7f429e61849e794569310b5
238370966634441304873792337937568791030
177,774
157,883
false
void ArthurOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, int *maskColors, GBool inlineImg) { unsigned char *buffer; unsigned int *dest; int x, y; ImageStream *imgStr; Guchar *pix; int i; double *ctm; QMatrix matrix; int is_identity_transform; buffer = (unsigned char *)gmalloc (width * height * 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); if (maskColors) { for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); for (x = 0; x < width; x++) { for (i = 0; i < colorMap->getNumPixelComps(); ++i) { if (pix[i] < maskColors[2*i] * 255|| pix[i] > maskColors[2*i+1] * 255) { *dest = *dest | 0xff000000; break; } } pix += colorMap->getNumPixelComps(); dest++; } } m_image = new QImage(buffer, width, height, QImage::Format_ARGB32); } else { for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } m_image = new QImage(buffer, width, height, QImage::Format_RGB32); } if (m_image == NULL || m_image->isNull()) { qDebug() << "Null image"; delete imgStr; return; } ctm = state->getCTM(); matrix.setMatrix(ctm[0] / width, ctm[1] / width, -ctm[2] / height, -ctm[3] / height, ctm[2] + ctm[4], ctm[3] + ctm[5]); m_painter->setMatrix(matrix, true); m_painter->drawImage( QPoint(0,0), *m_image ); delete m_image; m_image = 0; free (buffer); delete imgStr; }
[ "CWE-189" ]
poppler
7b2d314a61fd0e12f47c62996cb49ec0d1ba747a
145223011821522984832787544024029108709
177,775
28
true
void ArthurOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, int width, int height, GfxImageColorMap *colorMap, int *maskColors, GBool inlineImg) { unsigned char *buffer; unsigned int *dest; int x, y; ImageStream *imgStr; Guchar *pix; int i; double *ctm; QMatrix matrix; int is_identity_transform; buffer = (unsigned char *)gmallocn3(width, height, 4); /* TODO: Do we want to cache these? */ imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(), colorMap->getBits()); imgStr->reset(); /* ICCBased color space doesn't do any color correction * so check its underlying color space as well */ is_identity_transform = colorMap->getColorSpace()->getMode() == csDeviceRGB || (colorMap->getColorSpace()->getMode() == csICCBased && ((GfxICCBasedColorSpace*)colorMap->getColorSpace())->getAlt()->getMode() == csDeviceRGB); if (maskColors) { for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); for (x = 0; x < width; x++) { for (i = 0; i < colorMap->getNumPixelComps(); ++i) { if (pix[i] < maskColors[2*i] * 255|| pix[i] > maskColors[2*i+1] * 255) { *dest = *dest | 0xff000000; break; } } pix += colorMap->getNumPixelComps(); dest++; } } m_image = new QImage(buffer, width, height, QImage::Format_ARGB32); } else { for (y = 0; y < height; y++) { dest = (unsigned int *) (buffer + y * 4 * width); pix = imgStr->getLine(); colorMap->getRGBLine (pix, dest, width); } m_image = new QImage(buffer, width, height, QImage::Format_RGB32); } if (m_image == NULL || m_image->isNull()) { qDebug() << "Null image"; delete imgStr; return; } ctm = state->getCTM(); matrix.setMatrix(ctm[0] / width, ctm[1] / width, -ctm[2] / height, -ctm[3] / height, ctm[2] + ctm[4], ctm[3] + ctm[5]); m_painter->setMatrix(matrix, true); m_painter->drawImage( QPoint(0,0), *m_image ); delete m_image; m_image = 0; free (buffer); delete imgStr; }
[ "CWE-189" ]
poppler
7b2d314a61fd0e12f47c62996cb49ec0d1ba747a
328681969473388669211085267743237662516
177,775
157,884
false
DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e) : saml2md::DynamicMetadataProvider(e), m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)), m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)), m_encoded(true), m_trust(nullptr) { const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst); if (child && child->hasChildNodes()) { auto_ptr_char s(child->getFirstChild()->getNodeValue()); if (s.get() && *s.get()) { m_subst = s.get(); m_encoded = XMLHelper::getAttrBool(child, true, encoded); m_hashed = XMLHelper::getAttrString(child, nullptr, hashed); } } if (m_subst.empty()) { child = XMLHelper::getFirstChildElement(e, Regex); if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) { m_match = XMLHelper::getAttrString(child, nullptr, match); auto_ptr_char repl(child->getFirstChild()->getNodeValue()); if (repl.get() && *repl.get()) m_regex = repl.get(); } } if (!m_ignoreTransport) { child = XMLHelper::getFirstChildElement(e, _TrustEngine); string t = XMLHelper::getAttrString(child, nullptr, _type); if (!t.empty()) { TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child); if (!dynamic_cast<X509TrustEngine*>(trust)) { delete trust; throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin."); } m_trust.reset(dynamic_cast<X509TrustEngine*>(trust)); m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr)); } if (!m_trust.get() || !m_dummyCR.get()) throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true."); } }
[ "CWE-347" ]
shibboleth
b66cceb0e992c351ad5e2c665229ede82f261b16
11538925675754479849567947994472519439
177,795
40
true
DynamicMetadataProvider::DynamicMetadataProvider(const DOMElement* e) : saml2md::DynamicMetadataProvider(e), MetadataProvider(e), m_verifyHost(XMLHelper::getAttrBool(e, true, verifyHost)), m_ignoreTransport(XMLHelper::getAttrBool(e, false, ignoreTransport)), m_encoded(true), m_trust(nullptr) { const DOMElement* child = XMLHelper::getFirstChildElement(e, Subst); if (child && child->hasChildNodes()) { auto_ptr_char s(child->getFirstChild()->getNodeValue()); if (s.get() && *s.get()) { m_subst = s.get(); m_encoded = XMLHelper::getAttrBool(child, true, encoded); m_hashed = XMLHelper::getAttrString(child, nullptr, hashed); } } if (m_subst.empty()) { child = XMLHelper::getFirstChildElement(e, Regex); if (child && child->hasChildNodes() && child->hasAttributeNS(nullptr, match)) { m_match = XMLHelper::getAttrString(child, nullptr, match); auto_ptr_char repl(child->getFirstChild()->getNodeValue()); if (repl.get() && *repl.get()) m_regex = repl.get(); } } if (!m_ignoreTransport) { child = XMLHelper::getFirstChildElement(e, _TrustEngine); string t = XMLHelper::getAttrString(child, nullptr, _type); if (!t.empty()) { TrustEngine* trust = XMLToolingConfig::getConfig().TrustEngineManager.newPlugin(t.c_str(), child); if (!dynamic_cast<X509TrustEngine*>(trust)) { delete trust; throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin."); } m_trust.reset(dynamic_cast<X509TrustEngine*>(trust)); m_dummyCR.reset(XMLToolingConfig::getConfig().CredentialResolverManager.newPlugin(DUMMY_CREDENTIAL_RESOLVER, nullptr)); } if (!m_trust.get() || !m_dummyCR.get()) throw ConfigurationException("DynamicMetadataProvider requires an X509TrustEngine plugin unless ignoreTransport is true."); } }
[ "CWE-347" ]
shibboleth
b66cceb0e992c351ad5e2c665229ede82f261b16
313820794002673879698519839177687302127
177,795
157,898
false
static int nfs_readlink_req(struct nfs_priv *npriv, struct nfs_fh *fh, char **target) { uint32_t data[1024]; uint32_t *p; uint32_t len; struct packet *nfs_packet; /* * struct READLINK3args { * nfs_fh3 symlink; * }; * * struct READLINK3resok { * post_op_attr symlink_attributes; * nfspath3 data; * }; * * struct READLINK3resfail { * post_op_attr symlink_attributes; * } * * union READLINK3res switch (nfsstat3 status) { * case NFS3_OK: * READLINK3resok resok; * default: * READLINK3resfail resfail; * }; */ p = &(data[0]); p = rpc_add_credentials(p); p = nfs_add_fh3(p, fh); len = p - &(data[0]); nfs_packet = rpc_req(npriv, PROG_NFS, NFSPROC3_READLINK, data, len); if (IS_ERR(nfs_packet)) return PTR_ERR(nfs_packet); p = (void *)nfs_packet->data + sizeof(struct rpc_reply) + 4; p = nfs_read_post_op_attr(p, NULL); len = ntoh32(net_read_uint32(p)); /* new path length */ p++; *target = xzalloc(len + 1); return 0; }
[ "CWE-119" ]
pengutronix
574ce994016107ad8ab0f845a785f28d7eaa5208
165064796667373419921312233428470052444
177,796
41
true
static int nfs_readlink_req(struct nfs_priv *npriv, struct nfs_fh *fh, char **target) { uint32_t data[1024]; uint32_t *p; uint32_t len; struct packet *nfs_packet; /* * struct READLINK3args { * nfs_fh3 symlink; * }; * * struct READLINK3resok { * post_op_attr symlink_attributes; * nfspath3 data; * }; * * struct READLINK3resfail { * post_op_attr symlink_attributes; * } * * union READLINK3res switch (nfsstat3 status) { * case NFS3_OK: * READLINK3resok resok; * default: * READLINK3resfail resfail; * }; */ p = &(data[0]); p = rpc_add_credentials(p); p = nfs_add_fh3(p, fh); len = p - &(data[0]); nfs_packet = rpc_req(npriv, PROG_NFS, NFSPROC3_READLINK, data, len); if (IS_ERR(nfs_packet)) return PTR_ERR(nfs_packet); p = (void *)nfs_packet->data + sizeof(struct rpc_reply) + 4; p = nfs_read_post_op_attr(p, NULL); len = ntoh32(net_read_uint32(p)); /* new path length */ len = max_t(unsigned int, len, nfs_packet->len - sizeof(struct rpc_reply) - sizeof(uint32_t)); p++; *target = xzalloc(len + 1); return 0; }
[ "CWE-119" ]
pengutronix
574ce994016107ad8ab0f845a785f28d7eaa5208
52376305515786293225734978443916270796
177,796
157,899
false
static int nfs_readlink_reply(unsigned char *pkt, unsigned len) { uint32_t *data; char *path; int rlen; int ret; ret = rpc_check_reply(pkt, 1); if (ret) return ret; data = (uint32_t *)(pkt + sizeof(struct rpc_reply)); data++; rlen = ntohl(net_read_uint32(data)); /* new path length */ data++; path = (char *)data; } else { memcpy(nfs_path, path, rlen); nfs_path[rlen] = 0; }
[ "CWE-119" ]
pengutronix
84986ca024462058574432b5483f4bf9136c538d
197742048742816713437466148600234690021
177,797
42
true
static int nfs_readlink_reply(unsigned char *pkt, unsigned len) { uint32_t *data; char *path; unsigned int rlen; int ret; ret = rpc_check_reply(pkt, 1); if (ret) return ret; data = (uint32_t *)(pkt + sizeof(struct rpc_reply)); data++; rlen = ntohl(net_read_uint32(data)); /* new path length */ rlen = max_t(unsigned int, rlen, len - sizeof(struct rpc_reply) - sizeof(uint32_t)); data++; path = (char *)data; } else { memcpy(nfs_path, path, rlen); nfs_path[rlen] = 0; }
[ "CWE-119" ]
pengutronix
84986ca024462058574432b5483f4bf9136c538d
206056256559243150120680816426898705118
177,797
157,900
false
zsetdevice(i_ctx_t *i_ctx_p) { gx_device *dev = gs_currentdevice(igs); os_ptr op = osp; int code = 0; check_write_type(*op, t_device); if (dev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != dev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; }
[ "Other" ]
ghostscript
661e8d8fb8248c38d67958beda32f3a5876d0c3f
340004772641014275916898545695953737482
177,810
52
true
zsetdevice(i_ctx_t *i_ctx_p) { gx_device *odev = NULL, *dev = gs_currentdevice(igs); os_ptr op = osp; int code = dev_proc(dev, dev_spec_op)(dev, gxdso_current_output_device, (void *)&odev, 0); if (code < 0) return code; check_write_type(*op, t_device); if (odev->LockSafetyParams) { /* do additional checking if locked */ if(op->value.pdevice != odev) /* don't allow a different device */ return_error(gs_error_invalidaccess); } dev->ShowpageCount = 0; code = gs_setdevice_no_erase(igs, op->value.pdevice); if (code < 0) return code; make_bool(op, code != 0); /* erase page if 1 */ invalidate_stack_devices(i_ctx_p); clear_pagedevice(istate); return code; }
[ "Other" ]
ghostscript
661e8d8fb8248c38d67958beda32f3a5876d0c3f
59315764021980318626003459290825520793
177,810
157,910
false
void sum_update(const char *p, int32 len) { switch (cursum_type) { case CSUM_MD5: md5_update(&md, (uchar *)p, len); break; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: if (len + sumresidue < CSUM_CHUNK) { memcpy(md.buffer + sumresidue, p, len); sumresidue += len; } if (sumresidue) { int32 i = CSUM_CHUNK - sumresidue; memcpy(md.buffer + sumresidue, p, i); mdfour_update(&md, (uchar *)md.buffer, CSUM_CHUNK); len -= i; p += i; } while (len >= CSUM_CHUNK) { mdfour_update(&md, (uchar *)p, CSUM_CHUNK); len -= CSUM_CHUNK; p += CSUM_CHUNK; } sumresidue = len; if (sumresidue) memcpy(md.buffer, p, sumresidue); break; case CSUM_NONE: break; } }
[ "CWE-354" ]
samba
c252546ceeb0925eb8a4061315e3ff0a8c55b48b
337655106013087126363639454838638190943
177,812
54
true
void sum_update(const char *p, int32 len) { switch (cursum_type) { case CSUM_MD5: md5_update(&md, (uchar *)p, len); break; case CSUM_MD4: case CSUM_MD4_OLD: case CSUM_MD4_BUSTED: case CSUM_MD4_ARCHAIC: if (len + sumresidue < CSUM_CHUNK) { memcpy(md.buffer + sumresidue, p, len); sumresidue += len; } if (sumresidue) { int32 i = CSUM_CHUNK - sumresidue; memcpy(md.buffer + sumresidue, p, i); mdfour_update(&md, (uchar *)md.buffer, CSUM_CHUNK); len -= i; p += i; } while (len >= CSUM_CHUNK) { mdfour_update(&md, (uchar *)p, CSUM_CHUNK); len -= CSUM_CHUNK; p += CSUM_CHUNK; } sumresidue = len; if (sumresidue) memcpy(md.buffer, p, sumresidue); break; case CSUM_NONE: break; } }
[ "CWE-354" ]
samba
c252546ceeb0925eb8a4061315e3ff0a8c55b48b
127195280572279640618380038836318413135
177,812
157,912
false
char *auth_server(int f_in, int f_out, int module, const char *host, const char *addr, const char *leader) { char *users = lp_auth_users(module); char challenge[MAX_DIGEST_LEN*2]; char line[BIGPATHBUFLEN]; char **auth_uid_groups = NULL; int auth_uid_groups_cnt = -1; const char *err = NULL; int group_match = -1; char *tok, *pass; char opt_ch = '\0'; /* if no auth list then allow anyone in! */ if (!users || !*users) if (!users || !*users) return ""; gen_challenge(addr, challenge); io_printf(f_out, "%s%s\n", leader, challenge); return NULL; }
[ "CWE-354" ]
samba
9a480deec4d20277d8e20bc55515ef0640ca1e55
98721516615150795159214070101872089036
177,813
55
true
char *auth_server(int f_in, int f_out, int module, const char *host, const char *addr, const char *leader) { char *users = lp_auth_users(module); char challenge[MAX_DIGEST_LEN*2]; char line[BIGPATHBUFLEN]; char **auth_uid_groups = NULL; int auth_uid_groups_cnt = -1; const char *err = NULL; int group_match = -1; char *tok, *pass; char opt_ch = '\0'; /* if no auth list then allow anyone in! */ if (!users || !*users) if (!users || !*users) return ""; if (protocol_version < 21) { /* Don't allow a weak checksum for the password. */ rprintf(FERROR, "ERROR: protocol version is too old!\n"); exit_cleanup(RERR_PROTOCOL); } gen_challenge(addr, challenge); io_printf(f_out, "%s%s\n", leader, challenge); return NULL; }
[ "CWE-354" ]
samba
9a480deec4d20277d8e20bc55515ef0640ca1e55
143115557888664430123988818349954566324
177,813
157,913
false
static int get_next_block(bunzip_data *bd) { struct group_data *hufGroup; int dbufCount, dbufSize, groupCount, *base, *limit, selector, i, j, runPos, symCount, symTotal, nSelectors, byteCount[256]; int runCnt = runCnt; /* for compiler */ uint8_t uc, symToByte[256], mtfSymbol[256], *selectors; uint32_t *dbuf; unsigned origPtr, t; dbuf = bd->dbuf; dbufSize = bd->dbufSize; selectors = bd->selectors; /* In bbox, we are ok with aborting through setjmp which is set up in start_bunzip */ #if 0 /* Reset longjmp I/O error handling */ i = setjmp(bd->jmpbuf); if (i) return i; #endif /* Read in header signature and CRC, then validate signature. (last block signature means CRC is for whole file, return now) */ i = get_bits(bd, 24); j = get_bits(bd, 24); bd->headerCRC = get_bits(bd, 32); if ((i == 0x177245) && (j == 0x385090)) return RETVAL_LAST_BLOCK; if ((i != 0x314159) || (j != 0x265359)) return RETVAL_NOT_BZIP_DATA; /* We can add support for blockRandomised if anybody complains. There was some code for this in busybox 1.0.0-pre3, but nobody ever noticed that it didn't actually work. */ if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT; origPtr = get_bits(bd, 24); if ((int)origPtr > dbufSize) return RETVAL_DATA_ERROR; /* mapping table: if some byte values are never used (encoding things like ascii text), the compression code removes the gaps to have fewer symbols to deal with, and writes a sparse bitfield indicating which values were present. We make a translation table to convert the symbols back to the corresponding bytes. */ symTotal = 0; i = 0; t = get_bits(bd, 16); do { if (t & (1 << 15)) { unsigned inner_map = get_bits(bd, 16); do { if (inner_map & (1 << 15)) symToByte[symTotal++] = i; inner_map <<= 1; i++; } while (i & 15); i -= 16; } t <<= 1; i += 16; } while (i < 256); /* How many different Huffman coding groups does this block use? */ groupCount = get_bits(bd, 3); if (groupCount < 2 || groupCount > MAX_GROUPS) return RETVAL_DATA_ERROR; /* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding group. Read in the group selector list, which is stored as MTF encoded bit runs. (MTF=Move To Front, as each value is used it's moved to the start of the list.) */ for (i = 0; i < groupCount; i++) mtfSymbol[i] = i; nSelectors = get_bits(bd, 15); if (!nSelectors) return RETVAL_DATA_ERROR; for (i = 0; i < nSelectors; i++) { uint8_t tmp_byte; /* Get next value */ int n = 0; while (get_bits(bd, 1)) { if (n >= groupCount) return RETVAL_DATA_ERROR; n++; } /* Decode MTF to get the next selector */ tmp_byte = mtfSymbol[n]; while (--n >= 0) mtfSymbol[n + 1] = mtfSymbol[n]; mtfSymbol[0] = selectors[i] = tmp_byte; } /* Read the Huffman coding tables for each group, which code for symTotal literal symbols, plus two run symbols (RUNA, RUNB) */ symCount = symTotal + 2; for (j = 0; j < groupCount; j++) { uint8_t length[MAX_SYMBOLS]; /* 8 bits is ALMOST enough for temp[], see below */ unsigned temp[MAX_HUFCODE_BITS+1]; int minLen, maxLen, pp, len_m1; /* Read Huffman code lengths for each symbol. They're stored in a way similar to mtf; record a starting value for the first symbol, and an offset from the previous value for every symbol after that. (Subtracting 1 before the loop and then adding it back at the end is an optimization that makes the test inside the loop simpler: symbol length 0 becomes negative, so an unsigned inequality catches it.) */ len_m1 = get_bits(bd, 5) - 1; for (i = 0; i < symCount; i++) { for (;;) { int two_bits; if ((unsigned)len_m1 > (MAX_HUFCODE_BITS-1)) return RETVAL_DATA_ERROR; /* If first bit is 0, stop. Else second bit indicates whether to increment or decrement the value. Optimization: grab 2 bits and unget the second if the first was 0. */ two_bits = get_bits(bd, 2); if (two_bits < 2) { bd->inbufBitCount++; break; } /* Add one if second bit 1, else subtract 1. Avoids if/else */ len_m1 += (((two_bits+1) & 2) - 1); } /* Correct for the initial -1, to get the final symbol length */ length[i] = len_m1 + 1; } /* Find largest and smallest lengths in this group */ minLen = maxLen = length[0]; for (i = 1; i < symCount; i++) { if (length[i] > maxLen) maxLen = length[i]; else if (length[i] < minLen) minLen = length[i]; } /* Calculate permute[], base[], and limit[] tables from length[]. * * permute[] is the lookup table for converting Huffman coded symbols * into decoded symbols. base[] is the amount to subtract from the * value of a Huffman symbol of a given length when using permute[]. * * limit[] indicates the largest numerical value a symbol with a given * number of bits can have. This is how the Huffman codes can vary in * length: each code with a value>limit[length] needs another bit. */ hufGroup = bd->groups + j; hufGroup->minLen = minLen; hufGroup->maxLen = maxLen; /* Note that minLen can't be smaller than 1, so we adjust the base and limit array pointers so we're not always wasting the first entry. We do this again when using them (during symbol decoding). */ base = hufGroup->base - 1; limit = hufGroup->limit - 1; /* Calculate permute[]. Concurrently, initialize temp[] and limit[]. */ pp = 0; for (i = minLen; i <= maxLen; i++) { int k; temp[i] = limit[i] = 0; for (k = 0; k < symCount; k++) if (length[k] == i) hufGroup->permute[pp++] = k; } /* Count symbols coded for at each bit length */ /* NB: in pathological cases, temp[8] can end ip being 256. * That's why uint8_t is too small for temp[]. */ for (i = 0; i < symCount; i++) temp[length[i]]++; /* Calculate limit[] (the largest symbol-coding value at each bit * length, which is (previous limit<<1)+symbols at this level), and * base[] (number of symbols to ignore at each bit length, which is * limit minus the cumulative count of symbols coded for already). */ pp = t = 0; for (i = minLen; i < maxLen;) { unsigned temp_i = temp[i]; pp += temp_i; /* We read the largest possible symbol size and then unget bits after determining how many we need, and those extra bits could be set to anything. (They're noise from future symbols.) At each level we're really only interested in the first few bits, so here we set all the trailing to-be-ignored bits to 1 so they don't affect the value>limit[length] comparison. */ limit[i] = (pp << (maxLen - i)) - 1; pp <<= 1; t += temp_i; base[++i] = pp - t; } limit[maxLen] = pp + temp[maxLen] - 1; limit[maxLen+1] = INT_MAX; /* Sentinel value for reading next sym. */ base[minLen] = 0; } /* We've finished reading and digesting the block header. Now read this block's Huffman coded symbols from the file and undo the Huffman coding and run length encoding, saving the result into dbuf[dbufCount++] = uc */ /* Initialize symbol occurrence counters and symbol Move To Front table */ /*memset(byteCount, 0, sizeof(byteCount)); - smaller, but slower */ for (i = 0; i < 256; i++) { byteCount[i] = 0; mtfSymbol[i] = (uint8_t)i; } /* Loop through compressed symbols. */ runPos = dbufCount = selector = 0; for (;;) { int nextSym; /* Fetch next Huffman coding group from list. */ symCount = GROUP_SIZE - 1; if (selector >= nSelectors) return RETVAL_DATA_ERROR; hufGroup = bd->groups + selectors[selector++]; base = hufGroup->base - 1; limit = hufGroup->limit - 1; continue_this_group: /* Read next Huffman-coded symbol. */ /* Note: It is far cheaper to read maxLen bits and back up than it is to read minLen bits and then add additional bit at a time, testing as we go. Because there is a trailing last block (with file CRC), there is no danger of the overread causing an unexpected EOF for a valid compressed file. */ if (1) { /* As a further optimization, we do the read inline (falling back to a call to get_bits if the buffer runs dry). */ int new_cnt; while ((new_cnt = bd->inbufBitCount - hufGroup->maxLen) < 0) { /* bd->inbufBitCount < hufGroup->maxLen */ if (bd->inbufPos == bd->inbufCount) { nextSym = get_bits(bd, hufGroup->maxLen); goto got_huff_bits; } bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++]; bd->inbufBitCount += 8; }; bd->inbufBitCount = new_cnt; /* "bd->inbufBitCount -= hufGroup->maxLen;" */ nextSym = (bd->inbufBits >> new_cnt) & ((1 << hufGroup->maxLen) - 1); got_huff_bits: ; } else { /* unoptimized equivalent */ nextSym = get_bits(bd, hufGroup->maxLen); } /* Figure how many bits are in next symbol and unget extras */ i = hufGroup->minLen; while (nextSym > limit[i]) ++i; j = hufGroup->maxLen - i; if (j < 0) return RETVAL_DATA_ERROR; bd->inbufBitCount += j; /* Huffman decode value to get nextSym (with bounds checking) */ nextSym = (nextSym >> j) - base[i]; if ((unsigned)nextSym >= MAX_SYMBOLS) return RETVAL_DATA_ERROR; nextSym = hufGroup->permute[nextSym]; /* We have now decoded the symbol, which indicates either a new literal byte, or a repeated run of the most recent literal byte. First, check if nextSym indicates a repeated run, and if so loop collecting how many times to repeat the last literal. */ if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */ /* If this is the start of a new run, zero out counter */ if (runPos == 0) { runPos = 1; runCnt = 0; } /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at each bit position, add 1 or 2 instead. For example, 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. You can make any bit pattern that way using 1 less symbol than the basic or 0/1 method (except all bits 0, which would use no symbols, but a run of length 0 doesn't mean anything in this context). Thus space is saved. */ runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */ if (runPos < dbufSize) runPos <<= 1; ////The 32-bit overflow of runCnt wasn't yet seen, but probably can happen. ////This would be the fix (catches too large count way before it can overflow): //// if (runCnt > bd->dbufSize) { //// dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR", //// runCnt, bd->dbufSize); //// return RETVAL_DATA_ERROR; //// } goto end_of_huffman_loop; } dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR", dbufCount, runCnt, dbufCount + runCnt, dbufSize); return RETVAL_DATA_ERROR; literal used is the one at the head of the mtfSymbol array.) */ if (runPos != 0) { uint8_t tmp_byte; if (dbufCount + runCnt > dbufSize) { dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR", dbufCount, runCnt, dbufCount + runCnt, dbufSize); return RETVAL_DATA_ERROR; } tmp_byte = symToByte[mtfSymbol[0]]; byteCount[tmp_byte] += runCnt; while (--runCnt >= 0) dbuf[dbufCount++] = (uint32_t)tmp_byte; runPos = 0; } as part of a run above. Therefore 1 unused mtf position minus 2 non-literal nextSym values equals -1.) */ if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR; i = nextSym - 1; uc = mtfSymbol[i]; /* Adjust the MTF array. Since we typically expect to move only a first symbol in the mtf array, position 0, would have been handled as part of a run above. Therefore 1 unused mtf position minus 2 non-literal nextSym values equals -1.) */ if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR; i = nextSym - 1; uc = mtfSymbol[i]; uc = symToByte[uc]; /* We have our literal byte. Save it into dbuf. */ byteCount[uc]++; dbuf[dbufCount++] = (uint32_t)uc; /* Skip group initialization if we're not done with this group. Done * this way to avoid compiler warning. */ end_of_huffman_loop: if (--symCount >= 0) goto continue_this_group; } /* At this point, we've read all the Huffman-coded symbols (and repeated runs) for this block from the input stream, and decoded them into the intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. Now undo the Burrows-Wheeler transform on dbuf. See http://dogma.net/markn/articles/bwt/bwt.htm */ /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ j = 0; for (i = 0; i < 256; i++) { int tmp_count = j + byteCount[i]; byteCount[i] = j; j = tmp_count; } /* Figure out what order dbuf would be in if we sorted it. */ for (i = 0; i < dbufCount; i++) { uint8_t tmp_byte = (uint8_t)dbuf[i]; int tmp_count = byteCount[tmp_byte]; dbuf[tmp_count] |= (i << 8); byteCount[tmp_byte] = tmp_count + 1; } /* Decode first byte by hand to initialize "previous" byte. Note that it doesn't get output, and if the first three characters are identical it doesn't qualify as a run (hence writeRunCountdown=5). */ if (dbufCount) { uint32_t tmp; if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR; tmp = dbuf[origPtr]; bd->writeCurrent = (uint8_t)tmp; bd->writePos = (tmp >> 8); bd->writeRunCountdown = 5; } bd->writeCount = dbufCount; return RETVAL_OK; }
[ "CWE-190" ]
busybox
0402cb32df015d9372578e3db27db47b33d5c7b0
238413816495536863232825191293924303166
177,822
62
true
static int get_next_block(bunzip_data *bd) { struct group_data *hufGroup; int groupCount, *base, *limit, selector, i, j, symCount, symTotal, nSelectors, byteCount[256]; uint8_t uc, symToByte[256], mtfSymbol[256], *selectors; uint32_t *dbuf; unsigned origPtr, t; unsigned dbufCount, runPos; unsigned runCnt = runCnt; /* for compiler */ dbuf = bd->dbuf; selectors = bd->selectors; /* In bbox, we are ok with aborting through setjmp which is set up in start_bunzip */ #if 0 /* Reset longjmp I/O error handling */ i = setjmp(bd->jmpbuf); if (i) return i; #endif /* Read in header signature and CRC, then validate signature. (last block signature means CRC is for whole file, return now) */ i = get_bits(bd, 24); j = get_bits(bd, 24); bd->headerCRC = get_bits(bd, 32); if ((i == 0x177245) && (j == 0x385090)) return RETVAL_LAST_BLOCK; if ((i != 0x314159) || (j != 0x265359)) return RETVAL_NOT_BZIP_DATA; /* We can add support for blockRandomised if anybody complains. There was some code for this in busybox 1.0.0-pre3, but nobody ever noticed that it didn't actually work. */ if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT; origPtr = get_bits(bd, 24); if (origPtr > bd->dbufSize) return RETVAL_DATA_ERROR; /* mapping table: if some byte values are never used (encoding things like ascii text), the compression code removes the gaps to have fewer symbols to deal with, and writes a sparse bitfield indicating which values were present. We make a translation table to convert the symbols back to the corresponding bytes. */ symTotal = 0; i = 0; t = get_bits(bd, 16); do { if (t & (1 << 15)) { unsigned inner_map = get_bits(bd, 16); do { if (inner_map & (1 << 15)) symToByte[symTotal++] = i; inner_map <<= 1; i++; } while (i & 15); i -= 16; } t <<= 1; i += 16; } while (i < 256); /* How many different Huffman coding groups does this block use? */ groupCount = get_bits(bd, 3); if (groupCount < 2 || groupCount > MAX_GROUPS) return RETVAL_DATA_ERROR; /* nSelectors: Every GROUP_SIZE many symbols we select a new Huffman coding group. Read in the group selector list, which is stored as MTF encoded bit runs. (MTF=Move To Front, as each value is used it's moved to the start of the list.) */ for (i = 0; i < groupCount; i++) mtfSymbol[i] = i; nSelectors = get_bits(bd, 15); if (!nSelectors) return RETVAL_DATA_ERROR; for (i = 0; i < nSelectors; i++) { uint8_t tmp_byte; /* Get next value */ int n = 0; while (get_bits(bd, 1)) { if (n >= groupCount) return RETVAL_DATA_ERROR; n++; } /* Decode MTF to get the next selector */ tmp_byte = mtfSymbol[n]; while (--n >= 0) mtfSymbol[n + 1] = mtfSymbol[n]; mtfSymbol[0] = selectors[i] = tmp_byte; } /* Read the Huffman coding tables for each group, which code for symTotal literal symbols, plus two run symbols (RUNA, RUNB) */ symCount = symTotal + 2; for (j = 0; j < groupCount; j++) { uint8_t length[MAX_SYMBOLS]; /* 8 bits is ALMOST enough for temp[], see below */ unsigned temp[MAX_HUFCODE_BITS+1]; int minLen, maxLen, pp, len_m1; /* Read Huffman code lengths for each symbol. They're stored in a way similar to mtf; record a starting value for the first symbol, and an offset from the previous value for every symbol after that. (Subtracting 1 before the loop and then adding it back at the end is an optimization that makes the test inside the loop simpler: symbol length 0 becomes negative, so an unsigned inequality catches it.) */ len_m1 = get_bits(bd, 5) - 1; for (i = 0; i < symCount; i++) { for (;;) { int two_bits; if ((unsigned)len_m1 > (MAX_HUFCODE_BITS-1)) return RETVAL_DATA_ERROR; /* If first bit is 0, stop. Else second bit indicates whether to increment or decrement the value. Optimization: grab 2 bits and unget the second if the first was 0. */ two_bits = get_bits(bd, 2); if (two_bits < 2) { bd->inbufBitCount++; break; } /* Add one if second bit 1, else subtract 1. Avoids if/else */ len_m1 += (((two_bits+1) & 2) - 1); } /* Correct for the initial -1, to get the final symbol length */ length[i] = len_m1 + 1; } /* Find largest and smallest lengths in this group */ minLen = maxLen = length[0]; for (i = 1; i < symCount; i++) { if (length[i] > maxLen) maxLen = length[i]; else if (length[i] < minLen) minLen = length[i]; } /* Calculate permute[], base[], and limit[] tables from length[]. * * permute[] is the lookup table for converting Huffman coded symbols * into decoded symbols. base[] is the amount to subtract from the * value of a Huffman symbol of a given length when using permute[]. * * limit[] indicates the largest numerical value a symbol with a given * number of bits can have. This is how the Huffman codes can vary in * length: each code with a value>limit[length] needs another bit. */ hufGroup = bd->groups + j; hufGroup->minLen = minLen; hufGroup->maxLen = maxLen; /* Note that minLen can't be smaller than 1, so we adjust the base and limit array pointers so we're not always wasting the first entry. We do this again when using them (during symbol decoding). */ base = hufGroup->base - 1; limit = hufGroup->limit - 1; /* Calculate permute[]. Concurrently, initialize temp[] and limit[]. */ pp = 0; for (i = minLen; i <= maxLen; i++) { int k; temp[i] = limit[i] = 0; for (k = 0; k < symCount; k++) if (length[k] == i) hufGroup->permute[pp++] = k; } /* Count symbols coded for at each bit length */ /* NB: in pathological cases, temp[8] can end ip being 256. * That's why uint8_t is too small for temp[]. */ for (i = 0; i < symCount; i++) temp[length[i]]++; /* Calculate limit[] (the largest symbol-coding value at each bit * length, which is (previous limit<<1)+symbols at this level), and * base[] (number of symbols to ignore at each bit length, which is * limit minus the cumulative count of symbols coded for already). */ pp = t = 0; for (i = minLen; i < maxLen;) { unsigned temp_i = temp[i]; pp += temp_i; /* We read the largest possible symbol size and then unget bits after determining how many we need, and those extra bits could be set to anything. (They're noise from future symbols.) At each level we're really only interested in the first few bits, so here we set all the trailing to-be-ignored bits to 1 so they don't affect the value>limit[length] comparison. */ limit[i] = (pp << (maxLen - i)) - 1; pp <<= 1; t += temp_i; base[++i] = pp - t; } limit[maxLen] = pp + temp[maxLen] - 1; limit[maxLen+1] = INT_MAX; /* Sentinel value for reading next sym. */ base[minLen] = 0; } /* We've finished reading and digesting the block header. Now read this block's Huffman coded symbols from the file and undo the Huffman coding and run length encoding, saving the result into dbuf[dbufCount++] = uc */ /* Initialize symbol occurrence counters and symbol Move To Front table */ /*memset(byteCount, 0, sizeof(byteCount)); - smaller, but slower */ for (i = 0; i < 256; i++) { byteCount[i] = 0; mtfSymbol[i] = (uint8_t)i; } /* Loop through compressed symbols. */ runPos = dbufCount = selector = 0; for (;;) { int nextSym; /* Fetch next Huffman coding group from list. */ symCount = GROUP_SIZE - 1; if (selector >= nSelectors) return RETVAL_DATA_ERROR; hufGroup = bd->groups + selectors[selector++]; base = hufGroup->base - 1; limit = hufGroup->limit - 1; continue_this_group: /* Read next Huffman-coded symbol. */ /* Note: It is far cheaper to read maxLen bits and back up than it is to read minLen bits and then add additional bit at a time, testing as we go. Because there is a trailing last block (with file CRC), there is no danger of the overread causing an unexpected EOF for a valid compressed file. */ if (1) { /* As a further optimization, we do the read inline (falling back to a call to get_bits if the buffer runs dry). */ int new_cnt; while ((new_cnt = bd->inbufBitCount - hufGroup->maxLen) < 0) { /* bd->inbufBitCount < hufGroup->maxLen */ if (bd->inbufPos == bd->inbufCount) { nextSym = get_bits(bd, hufGroup->maxLen); goto got_huff_bits; } bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++]; bd->inbufBitCount += 8; }; bd->inbufBitCount = new_cnt; /* "bd->inbufBitCount -= hufGroup->maxLen;" */ nextSym = (bd->inbufBits >> new_cnt) & ((1 << hufGroup->maxLen) - 1); got_huff_bits: ; } else { /* unoptimized equivalent */ nextSym = get_bits(bd, hufGroup->maxLen); } /* Figure how many bits are in next symbol and unget extras */ i = hufGroup->minLen; while (nextSym > limit[i]) ++i; j = hufGroup->maxLen - i; if (j < 0) return RETVAL_DATA_ERROR; bd->inbufBitCount += j; /* Huffman decode value to get nextSym (with bounds checking) */ nextSym = (nextSym >> j) - base[i]; if ((unsigned)nextSym >= MAX_SYMBOLS) return RETVAL_DATA_ERROR; nextSym = hufGroup->permute[nextSym]; /* We have now decoded the symbol, which indicates either a new literal byte, or a repeated run of the most recent literal byte. First, check if nextSym indicates a repeated run, and if so loop collecting how many times to repeat the last literal. */ if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */ /* If this is the start of a new run, zero out counter */ if (runPos == 0) { runPos = 1; runCnt = 0; } /* Neat trick that saves 1 symbol: instead of or-ing 0 or 1 at each bit position, add 1 or 2 instead. For example, 1011 is 1<<0 + 1<<1 + 2<<2. 1010 is 2<<0 + 2<<1 + 1<<2. You can make any bit pattern that way using 1 less symbol than the basic or 0/1 method (except all bits 0, which would use no symbols, but a run of length 0 doesn't mean anything in this context). Thus space is saved. */ runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */ ////The 32-bit overflow of runCnt wasn't yet seen, but probably can happen. ////This would be the fix (catches too large count way before it can overflow): //// if (runCnt > bd->dbufSize) { //// dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR", //// runCnt, bd->dbufSize); //// return RETVAL_DATA_ERROR; //// } if (runPos < bd->dbufSize) runPos <<= 1; goto end_of_huffman_loop; } dbg("dbufCount:%d+runCnt:%d %d > dbufSize:%d RETVAL_DATA_ERROR", dbufCount, runCnt, dbufCount + runCnt, dbufSize); return RETVAL_DATA_ERROR; literal used is the one at the head of the mtfSymbol array.) */ if (runPos != 0) { uint8_t tmp_byte; if (dbufCount + runCnt > bd->dbufSize) { dbg("dbufCount:%u+runCnt:%u %u > dbufSize:%u RETVAL_DATA_ERROR", dbufCount, runCnt, dbufCount + runCnt, bd->dbufSize); return RETVAL_DATA_ERROR; } tmp_byte = symToByte[mtfSymbol[0]]; byteCount[tmp_byte] += runCnt; while ((int)--runCnt >= 0) dbuf[dbufCount++] = (uint32_t)tmp_byte; runPos = 0; } as part of a run above. Therefore 1 unused mtf position minus 2 non-literal nextSym values equals -1.) */ if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR; i = nextSym - 1; uc = mtfSymbol[i]; /* Adjust the MTF array. Since we typically expect to move only a first symbol in the mtf array, position 0, would have been handled as part of a run above. Therefore 1 unused mtf position minus 2 non-literal nextSym values equals -1.) */ if (dbufCount >= bd->dbufSize) return RETVAL_DATA_ERROR; i = nextSym - 1; uc = mtfSymbol[i]; uc = symToByte[uc]; /* We have our literal byte. Save it into dbuf. */ byteCount[uc]++; dbuf[dbufCount++] = (uint32_t)uc; /* Skip group initialization if we're not done with this group. Done * this way to avoid compiler warning. */ end_of_huffman_loop: if (--symCount >= 0) goto continue_this_group; } /* At this point, we've read all the Huffman-coded symbols (and repeated runs) for this block from the input stream, and decoded them into the intermediate buffer. There are dbufCount many decoded bytes in dbuf[]. Now undo the Burrows-Wheeler transform on dbuf. See http://dogma.net/markn/articles/bwt/bwt.htm */ /* Turn byteCount into cumulative occurrence counts of 0 to n-1. */ j = 0; for (i = 0; i < 256; i++) { int tmp_count = j + byteCount[i]; byteCount[i] = j; j = tmp_count; } /* Figure out what order dbuf would be in if we sorted it. */ for (i = 0; i < dbufCount; i++) { uint8_t tmp_byte = (uint8_t)dbuf[i]; int tmp_count = byteCount[tmp_byte]; dbuf[tmp_count] |= (i << 8); byteCount[tmp_byte] = tmp_count + 1; } /* Decode first byte by hand to initialize "previous" byte. Note that it doesn't get output, and if the first three characters are identical it doesn't qualify as a run (hence writeRunCountdown=5). */ if (dbufCount) { uint32_t tmp; if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR; tmp = dbuf[origPtr]; bd->writeCurrent = (uint8_t)tmp; bd->writePos = (tmp >> 8); bd->writeRunCountdown = 5; } bd->writeCount = dbufCount; return RETVAL_OK; }
[ "CWE-190" ]
busybox
0402cb32df015d9372578e3db27db47b33d5c7b0
312101605599426186472577359417874735416
177,822
157,918
false
BufCompressedFill (BufFilePtr f) { CompressedFile *file; register char_type *stackp, *de_stack; register char_type finchar; register code_int code, oldcode, incode; BufChar *buf, *bufend; file = (CompressedFile *) f->private; buf = f->buffer; bufend = buf + BUFFILESIZE; stackp = file->stackp; de_stack = file->de_stack; finchar = file->finchar; oldcode = file->oldcode; while (buf < bufend) { while (stackp > de_stack && buf < bufend) *buf++ = *--stackp; if (buf == bufend) break; if (oldcode == -1) break; code = getcode (file); if (code == -1) break; if ( (code == CLEAR) && file->block_compress ) { for ( code = 255; code >= 0; code-- ) file->tab_prefix[code] = 0; file->clear_flg = 1; file->free_ent = FIRST - 1; if ( (code = getcode (file)) == -1 ) /* O, untimely death! */ break; } incode = code; /* * Special case for KwKwK string. */ if ( code >= file->free_ent ) { *stackp++ = finchar; code = oldcode; } /* * Generate output characters in reverse order */ while ( code >= 256 ) { *stackp++ = file->tab_suffix[code]; code = file->tab_prefix[code]; } /* * Generate the new entry. */ if ( (code=file->free_ent) < file->maxmaxcode ) { file->tab_prefix[code] = (unsigned short)oldcode; file->tab_suffix[code] = finchar; file->free_ent = code+1; } /* * Remember previous code. */ oldcode = incode; } file->oldcode = oldcode; file->stackp = stackp; file->finchar = finchar; if (buf == f->buffer) { f->left = 0; return BUFFILEEOF; } f->bufp = f->buffer + 1; f->left = (buf - f->buffer) - 1; return f->buffer[0]; }
[ "CWE-119" ]
libxfont
d11ee5886e9d9ec610051a206b135a4cdc1e09a0
314816336443270992925734214319385584087
177,823
63
true
BufCompressedFill (BufFilePtr f) { CompressedFile *file; register char_type *stackp, *de_stack; register char_type finchar; register code_int code, oldcode, incode; BufChar *buf, *bufend; file = (CompressedFile *) f->private; buf = f->buffer; bufend = buf + BUFFILESIZE; stackp = file->stackp; de_stack = file->de_stack; finchar = file->finchar; oldcode = file->oldcode; while (buf < bufend) { while (stackp > de_stack && buf < bufend) *buf++ = *--stackp; if (buf == bufend) break; if (oldcode == -1) break; code = getcode (file); if (code == -1) break; if ( (code == CLEAR) && file->block_compress ) { for ( code = 255; code >= 0; code-- ) file->tab_prefix[code] = 0; file->clear_flg = 1; file->free_ent = FIRST - 1; if ( (code = getcode (file)) == -1 ) /* O, untimely death! */ break; } incode = code; /* * Special case for KwKwK string. */ if ( code >= file->free_ent ) { *stackp++ = finchar; code = oldcode; } /* * Generate output characters in reverse order */ while ( code >= 256 ) { if (stackp - de_stack >= STACK_SIZE - 1) return BUFFILEEOF; *stackp++ = file->tab_suffix[code]; code = file->tab_prefix[code]; } /* * Generate the new entry. */ if ( (code=file->free_ent) < file->maxmaxcode ) { file->tab_prefix[code] = (unsigned short)oldcode; file->tab_suffix[code] = finchar; file->free_ent = code+1; } /* * Remember previous code. */ oldcode = incode; } file->oldcode = oldcode; file->stackp = stackp; file->finchar = finchar; if (buf == f->buffer) { f->left = 0; return BUFFILEEOF; } f->bufp = f->buffer + 1; f->left = (buf - f->buffer) - 1; return f->buffer[0]; }
[ "CWE-119" ]
libxfont
d11ee5886e9d9ec610051a206b135a4cdc1e09a0
176288859918527814344787198280161772156
177,823
157,919
false
static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet) { char tmp[256]; struct dpc_ctx *ctx = c; switch (rr) { case RR_A: if (len != 4) return -1; ctx->addrs[ctx->cnt].scopeid = 0; memcpy(ctx->addrs[ctx->cnt++].addr, data, 4); break; case RR_AAAA: if (len != 16) return -1; ctx->addrs[ctx->cnt].family = AF_INET6; ctx->addrs[ctx->cnt].scopeid = 0; memcpy(ctx->addrs[ctx->cnt++].addr, data, 16); break; case RR_CNAME: if (__dn_expand(packet, (const unsigned char *)packet + 512, data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp)) strcpy(ctx->canon, tmp); break; } return 0; }
[ "CWE-119" ]
musl
45ca5d3fcb6f874bf5ba55d0e9651cef68515395
212099417602244187828055587331477277729
177,824
64
true
static int dns_parse_callback(void *c, int rr, const void *data, int len, const void *packet) { char tmp[256]; struct dpc_ctx *ctx = c; if (ctx->cnt >= MAXADDRS) return -1; switch (rr) { case RR_A: if (len != 4) return -1; ctx->addrs[ctx->cnt].scopeid = 0; memcpy(ctx->addrs[ctx->cnt++].addr, data, 4); break; case RR_AAAA: if (len != 16) return -1; ctx->addrs[ctx->cnt].family = AF_INET6; ctx->addrs[ctx->cnt].scopeid = 0; memcpy(ctx->addrs[ctx->cnt++].addr, data, 16); break; case RR_CNAME: if (__dn_expand(packet, (const unsigned char *)packet + 512, data, tmp, sizeof tmp) > 0 && is_valid_hostname(tmp)) strcpy(ctx->canon, tmp); break; } return 0; }
[ "CWE-119" ]
musl
45ca5d3fcb6f874bf5ba55d0e9651cef68515395
60029525500602919860744776503907800398
177,824
157,920
false
bool extractPages (const char *srcFileName, const char *destFileName) { char pathName[4096]; GooString *gfileName = new GooString (srcFileName); PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL); if (!doc->isOk()) { error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName); return false; } if (firstPage == 0 && lastPage == 0) { firstPage = 1; lastPage = doc->getNumPages(); } if (lastPage == 0) lastPage = doc->getNumPages(); if (firstPage == 0) if (firstPage == 0) firstPage = 1; if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) { error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName); return false; } for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) { snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo); GooString *gpageName = new GooString (pathName); { printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>", argDesc); } if (printVersion || printHelp) exitCode = 0; goto err0; } globalParams = new GlobalParams(); ok = extractPages (argv[1], argv[2]); if (ok) { exitCode = 0; } delete globalParams; err0: return exitCode; }
[ "CWE-20" ]
poppler
61f79b8447c3ac8ab5a26e79e0c28053ffdccf75
41887122719404523174993334902149265910
177,825
65
true
bool extractPages (const char *srcFileName, const char *destFileName) { char pathName[4096]; GooString *gfileName = new GooString (srcFileName); PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL); if (!doc->isOk()) { error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName); return false; } if (firstPage == 0 && lastPage == 0) { firstPage = 1; lastPage = doc->getNumPages(); } if (lastPage == 0) lastPage = doc->getNumPages(); if (firstPage == 0) if (firstPage == 0) firstPage = 1; if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) { error(errSyntaxError, -1, "'{0:s}' must contain '%d' if more than one page should be extracted", destFileName); return false; } // destFileName can have multiple %% and one %d // We use auxDestFileName to replace all the valid % appearances // by 'A' (random char that is not %), if at the end of replacing // any of the valid appearances there is still any % around, the // pattern is wrong char *auxDestFileName = strdup(destFileName); // %% can appear as many times as you want char *p = strstr(auxDestFileName, "%%"); while (p != NULL) { *p = 'A'; *(p + 1) = 'A'; p = strstr(p, "%%"); } // %d can appear only one time p = strstr(auxDestFileName, "%d"); if (p != NULL) { *p = 'A'; } // at this point any other % is wrong p = strstr(auxDestFileName, "%"); if (p != NULL) { error(errSyntaxError, -1, "'{0:s}' can only contain one '%d' pattern", destFileName); free(auxDestFileName); return false; } free(auxDestFileName); for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) { snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo); GooString *gpageName = new GooString (pathName); { printUsage ("pdfseparate", "<PDF-sourcefile> <PDF-pattern-destfile>", argDesc); } if (printVersion || printHelp) exitCode = 0; goto err0; } globalParams = new GlobalParams(); ok = extractPages (argv[1], argv[2]); if (ok) { exitCode = 0; } delete globalParams; err0: return exitCode; }
[ "CWE-20" ]
poppler
61f79b8447c3ac8ab5a26e79e0c28053ffdccf75
226017378882353720793476700179562068873
177,825
157,921
false
bool extractPages (const char *srcFileName, const char *destFileName) { char pathName[1024]; GooString *gfileName = new GooString (srcFileName); PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL); if (!doc->isOk()) { error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName); return false; } if (firstPage == 0 && lastPage == 0) { firstPage = 1; lastPage = doc->getNumPages(); } if (lastPage == 0) lastPage = doc->getNumPages(); if (firstPage == 0) firstPage = 1; if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) { error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName); return false; } for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) { sprintf (pathName, destFileName, pageNo); GooString *gpageName = new GooString (pathName); int errCode = doc->savePageAs(gpageName, pageNo); if ( errCode != errNone) { delete gpageName; delete gfileName; return false; } delete gpageName; } delete gfileName; return true; }
[ "CWE-119" ]
poppler
b8682d868ddf7f741e93b791588af0932893f95c
244634780333143587019078565382798831655
177,826
66
true
bool extractPages (const char *srcFileName, const char *destFileName) { char pathName[4096]; GooString *gfileName = new GooString (srcFileName); PDFDoc *doc = new PDFDoc (gfileName, NULL, NULL, NULL); if (!doc->isOk()) { error(errSyntaxError, -1, "Could not extract page(s) from damaged file ('{0:s}')", srcFileName); return false; } if (firstPage == 0 && lastPage == 0) { firstPage = 1; lastPage = doc->getNumPages(); } if (lastPage == 0) lastPage = doc->getNumPages(); if (firstPage == 0) firstPage = 1; if (firstPage != lastPage && strstr(destFileName, "%d") == NULL) { error(errSyntaxError, -1, "'{0:s}' must contain '%%d' if more than one page should be extracted", destFileName); return false; } for (int pageNo = firstPage; pageNo <= lastPage; pageNo++) { snprintf (pathName, sizeof (pathName) - 1, destFileName, pageNo); GooString *gpageName = new GooString (pathName); int errCode = doc->savePageAs(gpageName, pageNo); if ( errCode != errNone) { delete gpageName; delete gfileName; return false; } delete gpageName; } delete gfileName; return true; }
[ "CWE-119" ]
poppler
b8682d868ddf7f741e93b791588af0932893f95c
151037751520527895735005785354898270248
177,826
157,922
false
walk_string(fz_context *ctx, int uni, int remove, editable_str *str) { int rune; if (str->utf8 == NULL) return; do { char *s = &str->utf8[str->pos]; size_t len; int n = fz_chartorune(&rune, s); if (rune == uni) { /* Match. Skip over that one. */ str->pos += n; } else if (uni == 32) { /* We don't care if we're given whitespace * and it doesn't match the string. Don't * skip forward. Nothing to remove. */ break; } else if (rune == 32) { /* The string has a whitespace, and we * don't match it; that's forgivable as * PDF often misses out spaces. Remove this * if we are removing stuff. */ } else { /* Mismatch. No point in tracking through any more. */ str->pos = -1; break; } if (remove) { len = strlen(s+n); memmove(s, s+n, len+1); str->edited = 1; } } while (rune != uni); }
[ "CWE-125" ]
ghostscript
97096297d409ec6f206298444ba00719607e8ba8
260933823413348392755539962564037161558
177,832
70
true
walk_string(fz_context *ctx, int uni, int remove, editable_str *str) { int rune; if (str->utf8 == NULL || str->pos == -1) return; do { char *s = &str->utf8[str->pos]; size_t len; int n = fz_chartorune(&rune, s); if (rune == uni) { /* Match. Skip over that one. */ str->pos += n; } else if (uni == 32) { /* We don't care if we're given whitespace * and it doesn't match the string. Don't * skip forward. Nothing to remove. */ break; } else if (rune == 32) { /* The string has a whitespace, and we * don't match it; that's forgivable as * PDF often misses out spaces. Remove this * if we are removing stuff. */ } else { /* Mismatch. No point in tracking through any more. */ str->pos = -1; break; } if (remove) { len = strlen(s+n); memmove(s, s+n, len+1); str->edited = 1; } } while (rune != uni); }
[ "CWE-125" ]
ghostscript
97096297d409ec6f206298444ba00719607e8ba8
258102495955873121265660327401992670615
177,832
157,926
false
void red_channel_pipes_add_empty_msg(RedChannel *channel, int msg_type) { RingItem *link; RING_FOREACH(link, &channel->clients) { red_channel_client_pipe_add_empty_msg( SPICE_CONTAINEROF(link, RedChannelClient, channel_link), msg_type); } }
[ "CWE-399" ]
spice
53488f0275d6c8a121af49f7ac817d09ce68090d
246859488383496619201376958064716490992
177,835
71
true
void red_channel_pipes_add_empty_msg(RedChannel *channel, int msg_type) { RingItem *link, *next; RING_FOREACH_SAFE(link, next, &channel->clients) { red_channel_client_pipe_add_empty_msg( SPICE_CONTAINEROF(link, RedChannelClient, channel_link), msg_type); } }
[ "CWE-399" ]
spice
53488f0275d6c8a121af49f7ac817d09ce68090d
335972113688640103719320370363622760524
177,835
157,928
false
void red_channel_pipes_add_type(RedChannel *channel, int pipe_item_type) { RingItem *link; RING_FOREACH(link, &channel->clients) { red_channel_client_pipe_add_type( SPICE_CONTAINEROF(link, RedChannelClient, channel_link), pipe_item_type); } }
[ "CWE-399" ]
spice
53488f0275d6c8a121af49f7ac817d09ce68090d
261946911680290370969616922085083966153
177,836
72
true
void red_channel_pipes_add_type(RedChannel *channel, int pipe_item_type) { RingItem *link, *next; RING_FOREACH_SAFE(link, next, &channel->clients) { red_channel_client_pipe_add_type( SPICE_CONTAINEROF(link, RedChannelClient, channel_link), pipe_item_type); } }
[ "CWE-399" ]
spice
53488f0275d6c8a121af49f7ac817d09ce68090d
190053951808043701869694332992364951708
177,836
157,929
false
x11_open_helper(Buffer *b) { u_char *ucp; u_int proto_len, data_len; u_char *ucp; u_int proto_len, data_len; /* Check if the fixed size part of the packet is in buffer. */ if (buffer_len(b) < 12) return 0; debug2("Initial X11 packet contains bad byte order byte: 0x%x", ucp[0]); return -1; }
[ "CWE-264" ]
mindrot
1bf477d3cdf1a864646d59820878783d42357a1d
186655838205464964819117737453872627903
177,838
73
true
x11_open_helper(Buffer *b) { u_char *ucp; u_int proto_len, data_len; u_char *ucp; u_int proto_len, data_len; /* Is this being called after the refusal deadline? */ if (x11_refuse_time != 0 && (u_int)monotime() >= x11_refuse_time) { verbose("Rejected X11 connection after ForwardX11Timeout " "expired"); return -1; } /* Check if the fixed size part of the packet is in buffer. */ if (buffer_len(b) < 12) return 0; debug2("Initial X11 packet contains bad byte order byte: 0x%x", ucp[0]); return -1; }
[ "CWE-264" ]
mindrot
1bf477d3cdf1a864646d59820878783d42357a1d
16527654010321763311742650376565564635
177,838
157,931
false
_PUBLIC_ codepoint_t next_codepoint_handle_ext( struct smb_iconv_handle *ic, const char *str, size_t len, charset_t src_charset, size_t *bytes_consumed) { /* it cannot occupy more than 4 bytes in UTF16 format */ uint8_t buf[4]; smb_iconv_t descriptor; size_t ilen_orig; size_t ilen; size_t olen; char *outbuf; if ((str[0] & 0x80) == 0) { *bytes_consumed = 1; return (codepoint_t)str[0]; } * This is OK as we only support codepoints up to 1M (U+100000) */ ilen_orig = MIN(len, 5); ilen = ilen_orig; descriptor = get_conv_handle(ic, src_charset, CH_UTF16); if (descriptor == (smb_iconv_t)-1) { *bytes_consumed = 1; return INVALID_CODEPOINT; } /* * this looks a little strange, but it is needed to cope with * codepoints above 64k (U+1000) which are encoded as per RFC2781. */ olen = 2; outbuf = (char *)buf; smb_iconv(descriptor, &str, &ilen, &outbuf, &olen); if (olen == 2) { olen = 4; outbuf = (char *)buf; smb_iconv(descriptor, &str, &ilen, &outbuf, &olen); if (olen == 4) { /* we didn't convert any bytes */ *bytes_consumed = 1; return INVALID_CODEPOINT; } olen = 4 - olen; } else { olen = 2 - olen; } *bytes_consumed = ilen_orig - ilen; if (olen == 2) { return (codepoint_t)SVAL(buf, 0); } if (olen == 4) { /* decode a 4 byte UTF16 character manually */ return (codepoint_t)0x10000 + (buf[2] | ((buf[3] & 0x3)<<8) | (buf[0]<<10) | ((buf[1] & 0x3)<<18)); } /* no other length is valid */ return INVALID_CODEPOINT; }
[ "CWE-200" ]
samba
538d305de91e34a2938f5f219f18bf0e1918763f
7537344539298054773758251251687254208
177,839
74
README.md exists but content is empty.
Downloads last month
70