Finds the end of the HTTP response header in an array of bytes.

@todo This one's a little dirty...
182284
private static int findEndOfHeader(byte[] pBytes, int pEnd) {
        byte[] header = HTTP_HEADER_END.getBytes();

        // Normal condition, check all bytes
        for (int i = 0; i < pEnd - 4; i++) {  // Need 4 bytes to match
            if ((pBytes[i] == header[0]) && (pBytes[i + 1] == header[1]) && (pBytes[i + 2] == header[2]) && (pBytes[i + 3] == header[3])) {

                //System.err.println("FOUND END OF HEADER!");
                return i + 4;
            }
        }

        // Check last 3 bytes, to check if we have a partial match
        if ((pEnd - 1 >= 0) && (pBytes[pEnd - 1] == header[0])) {

            //System.err.println("FOUND LAST BYTE");
            return -2;  // LAST BYTE
        }
        else if ((pEnd - 2 >= 0) && (pBytes[pEnd - 2] == header[0]) && (pBytes[pEnd - 1] == header[1])) {

            //System.err.println("FOUND LAST TWO BYTES");
            return -3;  // LAST TWO BYTES
        }
        else if ((pEnd - 3 >= 0) && (pBytes[pEnd - 3] == header[0]) && (pBytes[pEnd - 2] == header[1]) && (pBytes[pEnd - 1] == header[2])) {

            //System.err.println("FOUND LAST THREE BYTES");
            return -4;  // LAST THREE BYTES
        }
        return -1;  // NO BYTES MATCH
    }
548671
function processHeader($lastLine = "\r\n") {
      $headers = array();
      $finished = false;

      while ( (!$finished) && (!feof($this->socket)) ) {
        $str = fgets($this->socket, 1024);
        $finished = ($str == $lastLine);
        if (!$finished) {
          list($hdr, $value) = preg_split('/: /', $str, 2);
// nasty workaround broken multiple same headers (eg. Set-Cookie headers) @FIXME
          if (isset($headers[$hdr])) {
            $headers[$hdr] .= '; ' . trim($value);
          } else {
            $headers[$hdr] = trim($value);
          }
        }
      }

      return $headers;
    }
873012
static public byte[] byteSubstring(byte[] bytes, int start, int end) {

        byte[] rc = null;

        if (0 > start || start > bytes.length || start > end) {
            // invalid start position
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Invalid start position in byteSubstring: " + start);
            }
        } else if (0 > end || end > bytes.length) {
            // invalid end position
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Invalid end position in byteSubstring: " + end);
            }
        } else {
            // now pull the substring
            int len = end - start;
            rc = new byte[len];
            System.arraycopy(bytes, start, rc, 0, len);
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "byteSubstring returning: [" + getEnglishString(rc) + "]");
        }
        return rc;
    }
124511
static private void encodeLastByte(byte last, int byteIndex, StringBuilder output) {
        int chunk;
        int offset = byteIndex % 5;
        switch (offset) {
            case 0:
                chunk = ((last & 0x07) << 2);
                output.append(lookupTable.charAt(chunk));
                break;
            case 1:
                chunk = ((last & 0x01) << 4);
                output.append(lookupTable.charAt(chunk));
                break;
            case 2:
                chunk = ((last & 0x0F) << 1);
                output.append(lookupTable.charAt(chunk));
                break;
            case 3:
                chunk = ((last & 0x03) << 3);
                output.append(lookupTable.charAt(chunk));
                break;
            case 4:
                break;
        }
    }
937514
private void parseHeaders(ReadStream s) throws IOException
  {
    int version = version();

    if (version < HTTP_1_0) {
      return;
    }

    if (version < HTTP_1_1) {
      killKeepalive("http client version less than 1.1: " + version);
    }

    byte []readBuffer = s.buffer();
    int readOffset = s.offset();
    int readLength = s.length();

    char []headerBuffer = _headerBuffer;
    headerBuffer[0] = 'z';
    int headerOffset = 1;
    _headerSize = 0;
    
    int readTail = readLength;
    if (headerBuffer.length - 1 < readTail - readOffset) {
      readTail = headerBuffer.length - 1;
    }

    boolean isLogFine = log.isLoggable(Level.FINE);

    while (true) {
      int ch;

      int keyOffset = headerOffset;

      // scan the key
      while (true) {
        if (readTail <= readOffset) {
          if ((readTail = fillHeaderTail(s, readOffset, headerOffset)) <= 0) {
            return;
          }

          readOffset = s.offset();
          headerOffset = _headerLength;
          headerBuffer = _headerBuffer;
        }

        ch = readBuffer[readOffset++];

        if (ch == '\n') {
          s.offset(readOffset);
          return;
        }
        else if (ch == ':') {
          break;
        }

        headerBuffer[headerOffset++] = (char) ch;
      }

      // strip trailing whitespace from key
      while (headerBuffer[headerOffset - 1] == ' ') {
        headerOffset--;
      }
      
      int keyLength = headerOffset - keyOffset;

      // skip whitespace
      do {
        if (readTail <= readOffset) {
          if ((readTail = fillHeaderTail(s, readOffset, headerOffset)) <= 0) {
            return;
          }

          readOffset = s.offset();
          headerOffset = _headerLength;
          headerBuffer = _headerBuffer;
        }
        
        ch = readBuffer[readOffset++];
      } while (ch == ' ' || ch == '\t');

      int valueOffset = headerOffset;

      // scan the value
      while (true) {
        if (readTail <= readOffset) {
          if ((readTail = fillHeaderTail(s, readOffset, headerOffset)) <= 0) {
            break;
          }

          readOffset = s.offset();
          headerOffset = _headerLength;
          headerBuffer = _headerBuffer;
        }

        if (ch == '\n') {
          int ch1 = readBuffer[readOffset];

          if (ch1 == ' ' || ch1 == '\t') {
            ch = ' ';
            readOffset++;

            if (headerBuffer[headerOffset - 1] == '\r') {
              headerOffset--;
            }
          }
          else
            break;
        }

        headerBuffer[headerOffset++] = (char) ch;

        ch = readBuffer[readOffset++];
      }

      while (headerBuffer[headerOffset - 1] <= ' ') {
        headerOffset--;
      }
      
      int headerSize = _headerSize;
      
      CharSegment []headerKeys = _headerKeys;
      CharSegment []headerValues = _headerValues;

      if (headerKeys.length <= headerSize) {
        _headerLength = headerOffset;
        extendHeaderBuffers();
        
        headerBuffer = _headerBuffer;
        headerKeys = _headerKeys;
        headerValues = _headerValues;
      }

      headerKeys[headerSize].init(headerBuffer, keyOffset, keyLength);

      int valueLength = headerOffset - valueOffset;
      headerValues[headerSize].init(headerBuffer, valueOffset, valueLength);

      if (isLogFine) {
        log.fine(headerKeys[headerSize] + ": " + headerValues[headerSize]
                 + " (" + dbgId() + ")");
      }

      if (addHeaderInt(headerBuffer, keyOffset, keyLength,
                       headerValues[headerSize])) {
        headerSize++;
      }

      _headerSize = headerSize;
    }
  }
249545
@Nonnull
  public ByteBuffer getByteBuffer() {
    if (base instanceof byte[] && offset >= BYTE_ARRAY_OFFSET) {
      final byte[] bytes = (byte[]) base;

      // the offset includes an object header... this is only needed for unsafe copies
      final long arrayOffset = offset - BYTE_ARRAY_OFFSET;

      // verify that the offset and length points somewhere inside the byte array
      // and that the offset can safely be truncated to a 32-bit integer
      if ((long) bytes.length < arrayOffset + numBytes) {
        throw new ArrayIndexOutOfBoundsException();
      }

      return ByteBuffer.wrap(bytes, (int) arrayOffset, numBytes);
    } else {
      return ByteBuffer.wrap(getBytes());
    }
  }
639042
private int findEndOfLine(final ByteBuf buffer) {
        int totalLength = buffer.readableBytes();
        int i = buffer.forEachByte(buffer.readerIndex() + offset, totalLength - offset, ByteProcessor.FIND_LF);
        if (i >= 0) {
            offset = 0;
            if (i > 0 && buffer.getByte(i - 1) == '\r') {
                i--;
            }
        } else {
            offset = totalLength;
        }
        return i;
    }
870005
private function curlSend()
    {
        $arguments = func_get_args();

        $httpMethod = array_shift($arguments);

        $data = array_shift($arguments);

        $endPointUrl = array_shift($arguments);

        $curlHandle = $this->curlInit();

        curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, $httpMethod);
        curl_setopt($curlHandle, CURLOPT_POSTFIELDS, (string)$data);
        curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array_merge(array('Content-Type: application/json'), $this->childauth));

        return $this->curlExec(
            $curlHandle,
            $endPointUrl
        );
    }
363508
@Override
    public int getHeaderLength() {
        try {
            final byte b = this.headers.getByte(0);
            // length is encoded as the number of 32-bit words, so to get number of bytes we must multiply by 4
            return (b & 0x0F) * 4;
        } catch (final IOException e) {
            throw new RuntimeException("unable to get the header length of the IP packet due to IOException", e);
        }
    }
1309592
private InputStream readHttpHeader() throws IOException {
    	
    	// this can be helpful when simply iterating over records, 
    	// looking for problems.
        Logger logger = Logger.getLogger(this.getClass().getName());
    	ArchiveRecordHeader h = this.getHeader();
    	
        // If judged a record that doesn't have an http header, return
        // immediately.
        String url = getHeader().getUrl();
        if(!url.startsWith("http") ||
            getHeader().getLength() <= MIN_HTTP_HEADER_LENGTH) {
            return null;
        }
        
        String statusLine;
        byte[] statusBytes;
        int eolCharCount = 0;
        int errOffset = 0;
        
        // Read status line, skipping any errant http headers found before it
        // This allows a larger number of 'corrupt' arcs -- where headers were accidentally
        // inserted before the status line to be readable
        while (true) {
        	statusBytes = LaxHttpParser.readRawLine(getIn());
        	eolCharCount = getEolCharsCount(statusBytes);
        	if (eolCharCount <= 0) {
        		throw new RecoverableIOException(
                "Failed to read http status where one was expected: " 
                + ((statusBytes == null) ? "" : new String(statusBytes)));
        	}
        
        	statusLine = EncodingUtil.getString(statusBytes, 0,
        			statusBytes.length - eolCharCount, ARCConstants.DEFAULT_ENCODING);
        	
        	// If a null or DELETED break immediately
        	if ((statusLine == null) || statusLine.startsWith("DELETED")) {
        		break;
        	}
        	
        	// If it's actually the status line, break, otherwise continue skipping any
        	// previous header values
        	if (!statusLine.contains(":") && StatusLine.startsWithHTTP(statusLine)) {
        		break;
        	}
        	
        	// Add bytes read to error "offset" to add to position
        	errOffset += statusBytes.length;
        }
        
        if (errOffset > 0) {
            this.incrementPosition(errOffset);
        }
        
        if ((statusLine == null) ||
                !StatusLine.startsWithHTTP(statusLine)) {
            if (statusLine.startsWith("DELETED")) {
                // Some old ARCs have deleted records like following:
                // http://vireo.gatech.edu:80/ebt-bin/nph-dweb/dynaweb/SGI_Developer/SGITCL_PG/@Generic__BookTocView/11108%3Btd%3D2 130.207.168.42 19991010131803 text/html 29202
                // DELETED_TIME=20000425001133_DELETER=Kurt_REASON=alexalist
                // (follows ~29K spaces)
                // For now, throw a RecoverableIOException so if iterating over
                // records, we keep going.  TODO: Later make a legitimate
                // ARCRecord from the deleted record rather than throw
                // exception.
                throw new DeletedARCRecordIOException(statusLine);
            } else {
            	this.errors.add(ArcRecordErrors.HTTP_STATUS_LINE_INVALID);
            }
        }

        try {
        	this.httpStatus = new StatusLine(statusLine);
        } catch(IOException e) {
        	logger.warning(e.getMessage() + " at offset: " + h.getOffset());
        	this.errors.add(ArcRecordErrors.HTTP_STATUS_LINE_EXCEPTION);
        }
        
        // Save off all bytes read.  Keep them as bytes rather than
        // convert to strings so we don't have to worry about encodings
        // though this should never be a problem doing http headers since
        // its all supposed to be ascii.
        ByteArrayOutputStream baos =
            new ByteArrayOutputStream(statusBytes.length + 4 * 1024);
        baos.write(statusBytes);
        
        // Now read rest of the header lines looking for the separation
        // between header and body.
        for (byte [] lineBytes = null; true;) {
            lineBytes = LaxHttpParser.readRawLine(getIn());
            eolCharCount = getEolCharsCount(lineBytes);
            if (eolCharCount <= 0) {
            	if (getIn().available() == 0) {
            		httpHeaderBytesRead += statusBytes.length;
                	logger.warning("HTTP header truncated at offset: " + h.getOffset());
            		this.errors.add(ArcRecordErrors.HTTP_HEADER_TRUNCATED);
            		this.setEor(true);
            		break;
            	} else {
            		throw new IOException("Failed reading http headers: " +
            				((lineBytes != null)? new String(lineBytes): null));
            	}
            } else {
            	httpHeaderBytesRead += lineBytes.length;
            }
            // Save the bytes read.
            baos.write(lineBytes);
            if ((lineBytes.length - eolCharCount) <= 0) {
                // We've finished reading the http header.
                break;
            }
        }
        
        byte [] headerBytes = baos.toByteArray();
        // Save off where body starts.
        this.getMetaData().setContentBegin(headerBytes.length);
        ByteArrayInputStream bais =
            new ByteArrayInputStream(headerBytes);
        if (!bais.markSupported()) {
            throw new IOException("ByteArrayInputStream does not support mark");
        }
        bais.mark(headerBytes.length);
        // Read the status line.  Don't let it into the parseHeaders function.
        // It doesn't know what to do with it.
        bais.read(statusBytes, 0, statusBytes.length);
        this.httpHeaders = LaxHttpParser.parseHeaders(bais,
            ARCConstants.DEFAULT_ENCODING);
        this.getMetaData().setStatusCode(Integer.toString(getStatusCode()));
        bais.reset();
        return bais;
    }
784250
function multipartDecode(response) {
    const message = new Uint8Array(response);

    /* Set a maximum length to search for the header boundaries, otherwise
       findToken can run for a long time
    */
    const maxSearchLength = 1000;


    // First look for the multipart mime header
    let separator = stringToUint8Array('\r\n\r\n');
    let headerIndex = findToken(message, separator, 0, maxSearchLength);
    if (headerIndex === -1) {
      throw new Error('Response message has no multipart mime header');
    }

    const header = uint8ArrayToString(message, 0, headerIndex);
    const boundaryString = identifyBoundary(header);
    if (!boundaryString) {
      throw new Error('Header of response message does not specify boundary');
    }

    const boundary = stringToUint8Array(boundaryString);
    const boundaryLength = boundary.length;
    const components = [];

    let offset = headerIndex + separator.length;

    // Loop until we cannot find any more boundaries
    let boundaryIndex;

    while (boundaryIndex !== -1) {
      // Search for the next boundary in the message, starting
      // from the current offset position
      boundaryIndex = findToken(message, boundary, offset);

      // If no further boundaries are found, stop here.
      if (boundaryIndex === -1) {
        break;
      }

      // Extract data from response message, excluding "\r\n"
      const spacingLength = 2;
      const length = boundaryIndex - offset - spacingLength;
      const data = response.slice(offset, offset + length);

      // Add the data to the array of results
      components.push(data);

      // Move the offset to the end of the current section,
      // plus the identified boundary
      offset += length + spacingLength + boundaryLength;
    }

    return components;
}
887348
protected function parseContentRange()
    {
        $contentRange = $this->request->header('content-range');
        if (empty($contentRange) === false) {
            return sscanf($contentRange, 'bytes %d-%d/%d');
        }

        $total = $end = (int) $this->request->header('content-length');

        return [0, $end, $total];
    }
452534
function(bytesIn,start,end,mode)
	{
		if(end - start > 16)
			end = start + 16;
		
		return bytesIn.slice(start, end);
	}
669619
function end(res, code) {
  if (code >= 400) {
    // check res object contains connect/express request and next structure
    if (res.req && res.req.next) {
      var error = new Error(http.STATUS_CODES[code]);
      error.status = code;
      return res.req.next(error);
    }

    // write human-friendly error message
    res.writeHead(code);
    res.end('[' + code + '] ' + http.STATUS_CODES[code]);
    return;
  }

  // just end with no body for 304 responses and such
  res.writeHead(code);
  res.end();
}
771955
def _complete_last_byte(self, packet):
        """"""
        padded_size = self.get_size()
        padding_bytes = padded_size - len(packet)
        if padding_bytes > 0:
            packet += Pad(padding_bytes).pack()
        return packet
1203680
def end_headers(self):
        """"""
        if self.request_version != 'HTTP/0.9':
            self._headers_buffer.append(b"\r\n")
            self.flush_headers()
885558
public String readHeader() throws IOException {
		byte[] buffer = new byte[BUFFER_SIZE];
		StringBuilder content = new StringBuilder(BUFFER_SIZE);
		while (content.indexOf(HEADER_END) == -1) {
			int amountRead = checkedRead(buffer, 0, BUFFER_SIZE);
			content.append(new String(buffer, 0, amountRead));
		}
		return content.substring(0, content.indexOf(HEADER_END));
	}