Пример #1
0
// memcpy exists to placate GCC.  Use memmove.
void*
memcpy(void *dst, const void *src, uint n)
{
  return memmove(dst, src, n);
}
Пример #2
0
void PathFinder::BuildPolyPath(const Vector3& startPos, const Vector3& endPos)
{
    // *** getting start/end poly logic ***

    float distToStartPoly, distToEndPoly;
    float startPoint[VERTEX_SIZE] = {startPos.y, startPos.z, startPos.x};
    float endPoint[VERTEX_SIZE] = {endPos.y, endPos.z, endPos.x};

    dtPolyRef startPoly = getPolyByLocation(startPoint, &distToStartPoly);
    dtPolyRef endPoly = getPolyByLocation(endPoint, &distToEndPoly);

    // we have a hole in our mesh
    // make shortcut path and mark it as NOPATH ( with flying exception )
    // its up to caller how he will use this info
    if (startPoly == INVALID_POLYREF || endPoly == INVALID_POLYREF)
    {
        DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: (startPoly == 0 || endPoly == 0)\n");
        BuildShortcut();
        m_type = (m_sourceUnit->GetTypeId() == TYPEID_UNIT && ((Creature*)m_sourceUnit)->CanFly())
                 ? PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH) : PATHFIND_NOPATH;
        return;
    }

    // we may need a better number here
    bool farFromPoly = (distToStartPoly > 7.0f || distToEndPoly > 7.0f);
    if (farFromPoly)
    {
        DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: farFromPoly distToStartPoly=%.3f distToEndPoly=%.3f\n", distToStartPoly, distToEndPoly);

        bool buildShotrcut = false;
        if (m_sourceUnit->GetTypeId() == TYPEID_UNIT)
        {
            Creature* owner = (Creature*)m_sourceUnit;

            Vector3 p = (distToStartPoly > 7.0f) ? startPos : endPos;
            if (m_sourceUnit->GetTerrain()->IsUnderWater(p.x, p.y, p.z))
            {
                DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: underWater case\n");
                if (owner->CanSwim())
                    buildShotrcut = true;
            }
            else
            {
                DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: flying case\n");
                if (owner->CanFly())
                    buildShotrcut = true;
            }
        }

        if (buildShotrcut)
        {
            BuildShortcut();
            m_type = PathType(PATHFIND_NORMAL | PATHFIND_NOT_USING_PATH);
            return;
        }
        else
        {
            float closestPoint[VERTEX_SIZE];
            // we may want to use closestPointOnPolyBoundary instead
            if (DT_SUCCESS == m_navMeshQuery->closestPointOnPoly(endPoly, endPoint, closestPoint))
            {
                dtVcopy(endPoint, closestPoint);
                setActualEndPosition(Vector3(endPoint[2], endPoint[0], endPoint[1]));
            }

            m_type = PATHFIND_INCOMPLETE;
        }
    }

    // *** poly path generating logic ***

    // start and end are on same polygon
    // just need to move in straight line
    if (startPoly == endPoly)
    {
        DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: (startPoly == endPoly)\n");

        BuildShortcut();

        m_pathPolyRefs[0] = startPoly;
        m_polyLength = 1;

        m_type = farFromPoly ? PATHFIND_INCOMPLETE : PATHFIND_NORMAL;
        DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: path type %d\n", m_type);
        return;
    }

    // look for startPoly/endPoly in current path
    // TODO: we can merge it with getPathPolyByPosition() loop
    bool startPolyFound = false;
    bool endPolyFound = false;
    uint32 pathStartIndex, pathEndIndex;

    if (m_polyLength)
    {
        for (pathStartIndex = 0; pathStartIndex < m_polyLength; ++pathStartIndex)
        {
            // here to catch few bugs
            MANGOS_ASSERT(m_pathPolyRefs[pathStartIndex] != INVALID_POLYREF || m_sourceUnit->PrintEntryError("PathFinder::BuildPolyPath"));

            if (m_pathPolyRefs[pathStartIndex] == startPoly)
            {
                startPolyFound = true;
                break;
            }
        }

        for (pathEndIndex = m_polyLength - 1; pathEndIndex > pathStartIndex; --pathEndIndex)
            if (m_pathPolyRefs[pathEndIndex] == endPoly)
            {
                endPolyFound = true;
                break;
            }
    }

    if (startPolyFound && endPolyFound)
    {
        DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: (startPolyFound && endPolyFound)\n");

        // we moved along the path and the target did not move out of our old poly-path
        // our path is a simple subpath case, we have all the data we need
        // just "cut" it out

        m_polyLength = pathEndIndex - pathStartIndex + 1;
        memmove(m_pathPolyRefs, m_pathPolyRefs + pathStartIndex, m_polyLength * sizeof(dtPolyRef));
    }
    else if (startPolyFound && !endPolyFound)
    {
        DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: (startPolyFound && !endPolyFound)\n");

        // we are moving on the old path but target moved out
        // so we have atleast part of poly-path ready

        m_polyLength -= pathStartIndex;

        // try to adjust the suffix of the path instead of recalculating entire length
        // at given interval the target cannot get too far from its last location
        // thus we have less poly to cover
        // sub-path of optimal path is optimal

        // take ~80% of the original length
        // TODO : play with the values here
        uint32 prefixPolyLength = uint32(m_polyLength * 0.8f + 0.5f);
        memmove(m_pathPolyRefs, m_pathPolyRefs + pathStartIndex, prefixPolyLength * sizeof(dtPolyRef));

        dtPolyRef suffixStartPoly = m_pathPolyRefs[prefixPolyLength-1];

        // we need any point on our suffix start poly to generate poly-path, so we need last poly in prefix data
        float suffixEndPoint[VERTEX_SIZE];
        if (DT_SUCCESS != m_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint))
        {
            // we can hit offmesh connection as last poly - closestPointOnPoly() don't like that
            // try to recover by using prev polyref
            --prefixPolyLength;
            suffixStartPoly = m_pathPolyRefs[prefixPolyLength-1];
            if (DT_SUCCESS != m_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint))
            {
                // suffixStartPoly is still invalid, error state
                BuildShortcut();
                m_type = PATHFIND_NOPATH;
                return;
            }
        }

        // generate suffix
        uint32 suffixPolyLength = 0;
        dtStatus dtResult = m_navMeshQuery->findPath(
                                suffixStartPoly,    // start polygon
                                endPoly,            // end polygon
                                suffixEndPoint,     // start position
                                endPoint,           // end position
                                &m_filter,            // polygon search filter
                                m_pathPolyRefs + prefixPolyLength - 1,    // [out] path
                                (int*)&suffixPolyLength,
                                MAX_PATH_LENGTH - prefixPolyLength); // max number of polygons in output path

        if (!suffixPolyLength || dtResult != DT_SUCCESS)
        {
            // this is probably an error state, but we'll leave it
            // and hopefully recover on the next Update
            // we still need to copy our preffix
            sLog.outError("%u's Path Build failed: 0 length path", m_sourceUnit->GetGUIDLow());
        }

        DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++  m_polyLength=%u prefixPolyLength=%u suffixPolyLength=%u \n", m_polyLength, prefixPolyLength, suffixPolyLength);

        // new path = prefix + suffix - overlap
        m_polyLength = prefixPolyLength + suffixPolyLength - 1;
    }
    else
    {
        DEBUG_FILTER_LOG(LOG_FILTER_PATHFINDING, "++ BuildPolyPath :: (!startPolyFound && !endPolyFound)\n");

        // either we have no path at all -> first run
        // or something went really wrong -> we aren't moving along the path to the target
        // just generate new path

        // free and invalidate old path data
        clear();

        dtStatus dtResult = m_navMeshQuery->findPath(
                                startPoly,          // start polygon
                                endPoly,            // end polygon
                                startPoint,         // start position
                                endPoint,           // end position
                                &m_filter,           // polygon search filter
                                m_pathPolyRefs,     // [out] path
                                (int*)&m_polyLength,
                                MAX_PATH_LENGTH);   // max number of polygons in output path

        if (!m_polyLength || dtResult != DT_SUCCESS)
        {
            // only happens if we passed bad data to findPath(), or navmesh is messed up
            sLog.outError("%u's Path Build failed: 0 length path", m_sourceUnit->GetGUIDLow());
            BuildShortcut();
            m_type = PATHFIND_NOPATH;
            return;
        }
    }

    // by now we know what type of path we can get
    if (m_pathPolyRefs[m_polyLength - 1] == endPoly && !(m_type & PATHFIND_INCOMPLETE))
        m_type = PATHFIND_NORMAL;
    else
        m_type = PATHFIND_INCOMPLETE;

    // generate the point-path out of our up-to-date poly-path
    BuildPointPath(startPoint, endPoint);
}
Пример #3
0
void cmd_boot(const char *arg, void *data, unsigned sz)
{
	unsigned kernel_actual;
	unsigned ramdisk_actual;
	static struct boot_img_hdr hdr;
	char *ptr = ((char*) data);
   unsigned page_size = 0;
   unsigned page_mask = 0;
   int strlen = 0;

	if (sz < sizeof(hdr)) {
		fastboot_fail("invalid bootimage header");
		return;
	}

	memcpy(&hdr, data, sizeof(hdr));

  printf("\n============================================================\n");
	hdr.magic[7] = '\0';
  printf("[%s] Android Boot IMG Hdr - Magic 	        : %s\n",MODULE_NAME,hdr.magic);
  printf("[%s] Android Boot IMG Hdr - Kernel Size 	: 0x%x\n",MODULE_NAME,hdr.kernel_size);
  printf("[%s] Android Boot IMG Hdr - Rootfs Size 	: 0x%x\n",MODULE_NAME,hdr.ramdisk_size);
  printf("[%s] Android Boot IMG Hdr - Page Size    	: 0x%x\n",MODULE_NAME,hdr.page_size);
  printf("============================================================\n");

	/* ensure commandline is terminated */
	hdr.cmdline[BOOT_ARGS_SIZE-1] = 0;

	if(hdr.page_size) {
		page_size = hdr.page_size;
		page_mask = page_size - 1;
		//page_mask = 2*1024 ; /*FIXME*/
	}
   else
   {
     printf("[FASTBOOT] Please specify the storage page-size in the boot header!\n");
     fastboot_fail("Please specify the storage page-size in the boot header!\n");
     return;
   }

	kernel_actual = ROUND_TO_PAGE(hdr.kernel_size, page_mask);
	ramdisk_actual = ROUND_TO_PAGE(hdr.ramdisk_size, page_mask);

	/* sz should have atleast raw boot image */
	if (page_size + kernel_actual + ramdisk_actual > sz) {
		fastboot_fail("incomplete bootimage");
		return;
	}

	memmove((void*) hdr.kernel_addr, (ptr + MKIMG_HEADER_SZ + BIMG_HEADER_SZ), hdr.kernel_size);
	memmove((void*) hdr.ramdisk_addr, (ptr + MKIMG_HEADER_SZ + BIMG_HEADER_SZ + kernel_actual), hdr.ramdisk_size);

  strlen += sprintf((const char*) hdr.cmdline, "%s lcm=%1d-%s", hdr.cmdline, DISP_IsLcmFound(), mt_disp_get_lcm_id());
  strlen += sprintf((const char*) hdr.cmdline, "%s fps=%1d", hdr.cmdline, mt_disp_get_lcd_time());

	fastboot_okay("");
	udc_stop();
   mtk_wdt_init(); //re-open wdt

  g_boot_mode = NORMAL_BOOT;

	boot_linux((void*) hdr.kernel_addr, (void*) hdr.tags_addr,
		   (const char*) hdr.cmdline, board_machtype(),
		   (void*) hdr.ramdisk_addr, hdr.ramdisk_size);
#if 0
  unsigned kernel_actual;
  unsigned ramdisk_actual;
  struct boot_img_hdr boot_hdr;
  unsigned int k_pg_cnt = 0;
  unsigned int r_pg_cnt = 0;
  unsigned int b_pg_cnt = 0;
  unsigned int size_b = 0;
  unsigned int pg_sz = 2*1024 ;
  int strlen = 0;

  /*copy hdr data from download_base*/
  memcpy(&boot_hdr, data, sizeof(boot_hdr));

  /* ensure commandline is terminated */
  boot_hdr.cmdline[BOOT_ARGS_SIZE-1] = 0;

  printf("\n============================================================\n");
	boot_hdr.magic[7] = '\0';
  printf("[%s] Android Boot IMG Hdr - Magic 	        : %s\n",MODULE_NAME,boot_hdr.magic);
  printf("[%s] Android Boot IMG Hdr - Kernel Size 	: 0x%x\n",MODULE_NAME,boot_hdr.kernel_size);
  printf("[%s] Android Boot IMG Hdr - Rootfs Size 	: 0x%x\n",MODULE_NAME,boot_hdr.ramdisk_size);
  printf("[%s] Android Boot IMG Hdr - Page Size    	: 0x%x\n",MODULE_NAME,boot_hdr.page_size);
  printf("============================================================\n");

  //***************
  //* check partition magic
  //*
  if (strncmp(boot_hdr.magic,BOOT_MAGIC, sizeof(BOOT_MAGIC))!=0) {
    printf("[%s] boot image header magic error\n", MODULE_NAME);
    return -1;
  }

  g_kmem_off =  (unsigned int)target_get_scratch_address();
  g_kmem_off = g_kmem_off + MKIMG_HEADER_SZ + BIMG_HEADER_SZ;


  if(boot_hdr.kernel_size % pg_sz == 0)
  {
    k_pg_cnt = boot_hdr.kernel_size / pg_sz;
  }
  else
  {
    k_pg_cnt = (boot_hdr.kernel_size / pg_sz) + 1;
  }

  if(boot_hdr.ramdisk_size % pg_sz == 0)
  {
    r_pg_cnt = boot_hdr.ramdisk_size / pg_sz;
  }
  else
  {
    r_pg_cnt = (boot_hdr.ramdisk_size / pg_sz) + 1;
  }

  printf(" > page count of kernel image = %d\n",k_pg_cnt);
  g_rmem_off = g_kmem_off + k_pg_cnt * pg_sz;

  printf(" > kernel mem offset = 0x%x\n",g_kmem_off);
  printf(" > rootfs mem offset = 0x%x\n",g_rmem_off);

  //***************
  //* specify boot image size
  //*
  g_bimg_sz = (k_pg_cnt + r_pg_cnt + 2)* pg_sz;
  printf(" > boot image size = 0x%x\n",g_bimg_sz);

  memmove((void*)CFG_BOOTIMG_LOAD_ADDR , g_kmem_off, boot_hdr.kernel_size);
  memmove((void*)CFG_RAMDISK_LOAD_ADDR , g_rmem_off, boot_hdr.ramdisk_size);

  //custom_port_in_kernel(g_boot_mode, commanline);
  //strlen += sprintf(commanline, "%s lcm=%1d-%s", commanline, DISP_IsLcmFound(), mt_disp_get_lcm_id());
  //strlen += sprintf(commanline, "%s fps=%1d", commanline, mt_disp_get_lcd_time());

  fastboot_okay("");

  udc_stop();

  mtk_wdt_init();
  boot_linux((void *)CFG_BOOTIMG_LOAD_ADDR, (unsigned *)CFG_BOOTARGS_ADDR,
		   (const char*) boot_hdr.cmdline, board_machtype(),
		   (void *)CFG_RAMDISK_LOAD_ADDR, boot_hdr.ramdisk_size);
#endif
}
Пример #4
0
void make_tunnel(int rsock, const char *remote)
{
	char buf[4096], *outbuf = NULL, *inbuf = NULL;
	int sock = -1, outlen = 0, inlen = 0;
	struct sockaddr *sa = NULL;
	const char *source;

	if (map_list) {
		if (!(source = map_find(remote))) {
			debug("<%d> connection from unmapped address (%s), disconnecting\n", rsock, remote);
			goto cleanup;
		}

		debug("<%d> mapped to %s\n", rsock, source);
	} else
		source = source_host;

	if (ircpass) {
		int i, ret;

		for (i = 0; i < sizeof(buf) - 1; i++) {
			if ((ret = read(rsock, buf + i, 1)) < 1)
				goto cleanup;
			if (buf[i] == '\n')
				break;
		}

		buf[i] = 0;
		
		if (i > 0 && buf[i - 1] == '\r')
			buf[i - 1] = 0;

		if (i == 4095 || strncasecmp(buf, "PASS ", 5)) {
			char *tmp;

			debug("<%d> irc proxy auth failed - junk\n", rsock);

			tmp = "ERROR :Closing link: Make your client send password first\r\n";
			if (write(rsock, tmp, strlen(tmp)) != strlen(tmp)) {
				// Do nothing. We're failing anyway.
			}
				
			goto cleanup;
		}

		if (strcmp(buf + 5, ircpass)) {
			char *tmp;

			debug("<%d> irc proxy auth failed - password incorrect\n", rsock);
			tmp = ":6tunnel 464 * :Password incorrect\r\nERROR :Closing link: Password incorrect\r\n";
			if (write(rsock, tmp, strlen(tmp)) != strlen(tmp)) {
				// Do nothing. We're failing anyway.
			}
			
			goto cleanup;
		}
		
		debug("<%d> irc proxy auth succeded\n", rsock);
	}
  
	if (!(sa = resolve_host(remote_host, remote_hint))) {
		debug("<%d> unable to resolve %s\n", rsock, remote_host);
		goto cleanup;
	}

	if ((sock = socket(sa->sa_family, SOCK_STREAM, 0)) == -1) {
		debug("<%d> unable to create socket (%s)\n", rsock, strerror(errno));
		goto cleanup;
	}

	free(sa);
	sa = NULL;

	if (source) {
		if (!(sa = resolve_host(source, local_hint))) {
			debug("<%d> unable to resolve source host (%s)\n", rsock, source);
			goto cleanup;
		}

		if (bind(sock, sa, (local_hint == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
			debug("<%d> unable to bind to source host (%s)\n", rsock, source);
			goto cleanup;
		}

		free(sa);
		sa = NULL;
	}

	sa = resolve_host(remote_host, remote_hint);

	((struct sockaddr_in*) sa)->sin_port = htons(remote_port);

	if (connect(sock, sa, (sa->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6))) {
		debug("<%d> connection refused (%s,%d)\n", rsock, remote_host, remote_port);
		goto cleanup;
	}

	free(sa);
	sa = NULL;

	debug("<%d> connected to %s,%d\n", rsock, remote_host, remote_port);

	if (ircsendpass) {
		snprintf(buf, 4096, "PASS %s\r\n", ircsendpass);
		if (write(sock, buf, strlen(buf)) != strlen(buf))
			goto cleanup;
	}

	for (;;) {
		fd_set rds, wds;
		int ret, sent;

		FD_ZERO(&rds);
		FD_SET(sock, &rds);
		FD_SET(rsock, &rds);

		FD_ZERO(&wds);
		if (outbuf && outlen)
			FD_SET(rsock, &wds);
		if (inbuf && inlen)
			FD_SET(sock, &wds);
    
		ret = select((sock > rsock) ? (sock + 1) : (rsock + 1), &rds, &wds, NULL, NULL);

		if (FD_ISSET(rsock, &wds)) {
			sent = write(rsock, outbuf, outlen);

			if (sent < 1)
				goto cleanup;

			if (sent == outlen) {
				free(outbuf);
				outbuf = NULL;
				outlen = 0;
			} else {
				memmove(outbuf, outbuf + sent, outlen - sent);
				outlen -= sent;
			}
		}

		if (FD_ISSET(sock, &wds)) {
			sent = write(sock, inbuf, inlen);

			if (sent < 1)
				goto cleanup;

			if (sent == inlen) {
				free(inbuf);
				inbuf = NULL;
				inlen = 0;
			} else {
				memmove(inbuf, inbuf + sent, inlen - sent);
				inlen -= sent;
			}
		}

		if (FD_ISSET(sock, &rds)) {
			if ((ret = read(sock, buf, 4096)) < 1)
				goto cleanup;

			if (hexdump) {
				printf("<%d> recvfrom %s,%d\n", rsock, remote_host, remote_port);
				print_hexdump(buf, ret);
			}
			
			sent = write(rsock, buf, ret);

			if (sent < 1)
				goto cleanup;
			
			if (sent < ret) {
				outbuf = xrealloc(outbuf, outlen + ret - sent);
				memcpy(outbuf + outlen, buf + sent, ret - sent);
				outlen = ret - sent;
			}
		}

		if (FD_ISSET(rsock, &rds)) {
			if ((ret = read(rsock, buf, 4096)) < 1)
				goto cleanup;

			if (hexdump) {
				printf("<%d> sendto %s,%d\n", rsock, remote_host, remote_port);
				print_hexdump(buf, ret);
			}

			sent = write(sock, buf, ret);

			if (sent < 1)
				goto cleanup;

			if (sent < ret) {
				inbuf = xrealloc(inbuf, inlen + ret - sent);
				memcpy(inbuf + inlen, buf + sent, ret - sent);
				inlen = ret - sent;
			}
		}
	}


cleanup:
	if (sa)
		free(sa);

	close(rsock);

	if (sock != -1)
		close(sock);
}
Пример #5
0
/**
 * Processes a single file.
 * @returns 0 if successfully processed.
 *          -2 if wrong format.
 *          other error code on failure.
 * @param   pszFile         Name of the file to process.
 * @param   pszFilePattern  File pattern to match pszFile with.
 * @author  knut st. osmundsen ([email protected])
 */
int ProcessFile(const char *pszFile1, unsigned long cbFile1, const char *pszFilePattern)
{
    int             rc = 0;
    FILESTATUS3     fst3;
    int             cchPattern = strlen(pszFilePattern);
    char            szFile2[CCHMAXPATH];
    char            szPattern[CCHMAXPATH];
    const char *    pszFileName;
    const char *    pszPatternName;


    /*
     * Correct the pattern.
     */
    memcpy(szPattern, pszFilePattern, cchPattern+1);
    if (szPattern[cchPattern - 1] == '\\' || szPattern[cchPattern - 1] == '/')
        szPattern[cchPattern++] = '*';
    else
    {
        if (!DosQueryPathInfo((PSZ)pszFilePattern, FIL_STANDARD, &fst3, sizeof(fst3)))
        {
            if (fst3.attrFile & FILE_DIRECTORY)
            {
                szPattern[cchPattern++] = '\\';
                szPattern[cchPattern++] = '*';
            }
        }
    }
    szPattern[cchPattern] = '\0';


    /*
     * Get the filename part of pszFile1.
     */
    pszFileName = strrchr(pszFile1, '\\');
    if (!pszFileName)
        pszFileName = strrchr(pszFile1, '/');
    if (!pszFileName)
        pszFileName = strchr(pszFile1, ':');
    if (!pszFileName)
        pszFileName = pszFile1 - 1;
    pszFileName++;


    /*
     * Get the filename portion of szPattern.
     */
    pszPatternName = strrchr(szPattern, '\\');
    if (!pszPatternName)
        pszPatternName = strrchr(szPattern, '/');
    if (!pszPatternName)
        pszPatternName = strchr(szPattern, ':');
    if (!pszPatternName)
        pszPatternName = szPattern - 1;
    pszPatternName++;


    /*
     * Edit the input name according to the pattern.
     */
    rc = DosEditName(1, (PSZ)pszFileName, (PSZ)pszPatternName, szFile2, sizeof(szFile2));
    if (!rc)
    {
        /*
         * Make fully qualified name.
         */
        if (pszPatternName == szPattern)
        {
            memmove(szFile2 + (int)pszFileName - (int)pszFile1, szFile2, strlen(szFile2) + 1);
            memcpy(szFile2, pszFile1, (int)pszFileName - (int)pszFile1);
        }
        else
        {
            memmove(szFile2 + (int)pszPatternName - (int)szPattern, szFile2, strlen(szFile2) + 1);
            memcpy(szFile2, szPattern, (int)pszPatternName - (int)szPattern);
        }

        /*
         * Check for existance of target.
         */
        rc = DosQueryPathInfo(szFile2, FIL_STANDARD, &fst3, sizeof(fst3));
        if (rc == NO_ERROR && !(fst3.attrFile & FILE_DIRECTORY))
        {
            ULONG   ulAction = 0;
            ULONG   cbFile2 = fst3.cbFile;
            HFILE   hFile1 = NULLHANDLE;
            HFILE   hFile2 = NULLHANDLE;

            rc = DosOpen(szFile2, &hFile2, &ulAction, 0, FILE_NORMAL,
                         OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS,
                         OPEN_FLAGS_SEQUENTIAL | OPEN_ACCESS_READONLY | OPEN_SHARE_DENYNONE,
                         NULL);
            if (!rc)
            {
                ulAction = 0;
                rc = DosOpen((PSZ)pszFile1, &hFile1, &ulAction, 0, FILE_NORMAL,
                             OPEN_ACTION_FAIL_IF_NEW | OPEN_ACTION_OPEN_IF_EXISTS,
                             OPEN_FLAGS_SEQUENTIAL | OPEN_ACCESS_READONLY | OPEN_SHARE_DENYNONE,
                             NULL);
                if (!rc)
                {
                    unsigned long   cMismatches = 0;
                    unsigned long   offRead = 0;

                    while (cbFile1 > 0 && cbFile2 > 0)
                    {
                        static char szBuffer1[0x10000];
                        static char szBuffer2[0x10000];
                        ULONG       cbRead1;
                        ULONG       cbRead2;
                        APIRET      rc1;
                        APIRET      rc2;

                        rc1 = DosRead(hFile1, &szBuffer1[0], min(sizeof(szBuffer1), cbFile1), &cbRead1);
                        cbFile1 -= cbRead1;

                        rc2 = DosRead(hFile2, &szBuffer2[0], min(sizeof(szBuffer2), cbFile2), &cbRead2);
                        cbFile2 -= cbRead2;

                        if (!rc1 && !rc2)
                        {
                            int cbCmp = min(cbRead1, cbRead2);

                            /*
                             * Check if equal using fast compare.
                             */
                            if (memcmp(&szBuffer1[0], &szBuffer2[0], cbCmp))
                            {
                                int i;
                                /*
                                 * Wasn't equal. Display mismatches using slow byte by byte compare.
                                 */
                                for (i = 0; i < cbCmp; i++)
                                {
                                    if (szBuffer1[i] != szBuffer2[i])
                                    {
                                        if (!options.fQuiet)
                                        {
                                            if (cMismatches++ == 0)
                                                printf("Mismatch comparing '%s' and '%s'.\n", pszFile1, szFile2);
                                            printf("at 0x%08x 0x%02x (%c) != 0x%02 (%c)\n",
                                                   offRead + i,
                                                   szBuffer1[i], isprint(szBuffer1[i]) ? szBuffer1[i] : ' ',
                                                   szBuffer2[i], isprint(szBuffer2[i]) ? szBuffer2[i] : ' ');
                                        }
                                        else
                                            cMismatches++;
                                    }
                                }
                            }

                            /*
                             * Check if last read and size is different.
                             */
                            if (cbRead1 != cbRead2)
                            {
                                if (!options.fQuiet)
                                {
                                    if (cMismatches == 0)
                                        printf("Mismatch comparing '%s' and '%s'.\n", pszFile1, szFile2);
                                    printf("Length differs. %d != %d\n",
                                           offRead + cbRead1 + cbFile1,
                                           offRead + cbRead2 + cbFile2);
                                    printf("%d differences so far\n", cMismatches);
                                }
                                rc = 1;
                                break;
                            }

                            /*
                             * Last read?
                             */
                            if (!cbFile1 || !cbFile2)
                            {
                                if (!options.fQuiet)
                                {
                                    if (cMismatches > 0)
                                    {
                                        if (cMismatches == 0)
                                            printf("Mismatch comparing '%s' and '%s'.\n", pszFile1, szFile2);
                                        printf("%d differences\n", cMismatches);
                                    }
                                    else
                                        printf("Successfull. '%s' matches '%s'.\n", pszFile1, szFile2);
                                }
                            }
                        }
                        else
                        {
                            /*
                             * Read Error.
                             */
                            if (rc1)
                                printf("Error: failed to read from '%s'. rc=%d\n", pszFile1, rc1);
                            if (rc2)
                                printf("Error: failed to read from '%s'. rc=%d\n", szFile2, rc2);
                            rc = rc1 ? rc1 : rc2;
                            break;
                        }
                    }

                    DosClose(hFile1);

                    /*
                     * Return number of errors.
                     */
                    if (cMismatches && !rc)
                        rc = cMismatches;
                }
                else
                    fprintf(stderr, "(SYS%04d): Could not open file '%s'.\n", rc, pszFile1);

                DosClose(hFile2);
            }
            else
                fprintf(stderr, "(SYS%04d): Could not open file '%s'.\n", rc, szFile2);
        }
        else
        {
            if (rc)
                fprintf(stderr, "(SYS%04d): File '%s' was not found.\n", rc, szFile2);
            else
                fprintf(stderr, "Error: Can't compare a file with a directory (%s).\n", szFile2);
        }
    }
    else
        fprintf(stderr, "Internal error DosEditName(1, '%s','%s',..) -> rc=%d\n", pszFileName, pszPatternName, rc);

    return rc;
}
Пример #6
0
char *passtrIDLConst(char *pcBuf, char *pcConst)
{
  char		*p, ch, lch;
  char		*dst;
  char		code = 1, lcode;
  unsigned long	chrCnt = 0;
  unsigned long	multiline = 0;

  if ( *pcConst != '\'' && *pcConst != '"' )
    return strcpy(pcBuf,pcConst);

  pcConst++;
  dst = pcBuf;

  for(;;)
  {
    ch = *(pcConst++);
    if ( (ch=='\'' || ch=='\"') && !*pcConst )
      break;    
    if ( !ch ) break;

    if ( ch == '\'' )
      *(dst++) = '\'';
    else if ( ch == '\\' )
    {
      ch = *pcConst;
      lcode = code;
      code = 0;
      switch ( ch )
      {
        case 'r':
          code = 0x0D;
          pcConst++;
          break;
        case 'n':
          code = 0x0A;
          pcConst++;
          break;
        case 't':
          code = 0x09;
          pcConst++;
          break;
        case '\\':
          if ( lcode )
            *(dst++) = '\'';
          *(dst++) = '\\';
          pcConst++;
          code = 0;
          continue;
        default:
          code = strtol(pcConst, &p, 0);
          if ( pcConst == p )
          {
            code = lcode;
            continue;
          }
          else
            pcConst = p;
      }

      if ( code )
      {
        if ( !lcode )
          *(dst++) = '\'';
        dst += sprintf( dst, "#$%.2X", code);
        chrCnt += 5;
        continue;
      }
    }

    if ( chrCnt >= LINE_LENGTH )
    {
      chrCnt = 0;
      if ( !code ) *(dst++) = '\'';
      if ( !multiline )
      {
        memmove(pcBuf+3,pcBuf,dst-pcBuf);
        memcpy(pcBuf,"\n  ",3);
        dst += 3;
      }
      memcpy(dst,"+\n  \'",5);
      dst += 5;
      code = 0;
      multiline = 1;
    }
    else
      if ( code )
      {
        *(dst++) = '\'';
        code = 0;
        chrCnt++;
      }
    *(dst++) = ch;
    chrCnt++;
    lch = ch;
  }

  if ( !code && ( lch != '\'' ) )
  {
    if ( lch == '"' ) dst--;
    *(unsigned short *)(dst) = '\0\'';
  }
  else
    *dst = '\0';
  return pcBuf;
}
Пример #7
0
int
MoveLayer (int old_index, int new_index)
{
  int group_of_layer[MAX_LAYER + 2], l, g, i;
  LayerType saved_layer;
  int saved_group;

  AddLayerChangeToUndoList (old_index, new_index);
  IncrementUndoSerialNumber ();

  if (old_index < -1 || old_index >= max_copper_layer)
    {
      Message ("Invalid old layer %d for move: must be -1..%d\n",
	       old_index, max_copper_layer - 1);
      return 1;
    }
  if (new_index < -1 || new_index > max_copper_layer || new_index >= MAX_LAYER)
    {
      Message ("Invalid new layer %d for move: must be -1..%d\n",
	       new_index, max_copper_layer);
      return 1;
    }
  if (old_index == new_index)
    return 0;

  if (new_index == -1
      && LastLayerInComponentGroup (old_index))
    {
      gui->confirm_dialog ("You can't delete the last top-side layer\n", "Ok", NULL);
      return 1;
    }

  if (new_index == -1
      && LastLayerInSolderGroup (old_index))
    {
      gui->confirm_dialog ("You can't delete the last bottom-side layer\n", "Ok", NULL);
      return 1;
    }

  for (l = 0; l < MAX_LAYER+2; l++)
    group_of_layer[l] = -1;

  for (g = 0; g < MAX_LAYER; g++)
    for (i = 0; i < PCB->LayerGroups.Number[g]; i++)
      group_of_layer[PCB->LayerGroups.Entries[g][i]] = g;

  if (old_index == -1)
    {
      LayerType *lp;
      if (max_copper_layer == MAX_LAYER)
	{
	  Message ("No room for new layers\n");
	  return 1;
	}
      /* Create a new layer at new_index. */
      lp = &PCB->Data->Layer[new_index];
      memmove (&PCB->Data->Layer[new_index + 1],
	       &PCB->Data->Layer[new_index],
	       (max_copper_layer + 2 - new_index) * sizeof (LayerType));
      memmove (&group_of_layer[new_index + 1],
	       &group_of_layer[new_index],
	       (max_copper_layer + 2 - new_index) * sizeof (int));
      max_copper_layer++;
      memset (lp, 0, sizeof (LayerType));
      lp->On = 1;
      lp->Name = strdup ("New Layer");
      lp->Color = Settings.LayerColor[new_index];
      lp->SelectedColor = Settings.LayerSelectedColor[new_index];
      for (l = 0; l < max_copper_layer; l++)
	if (LayerStack[l] >= new_index)
	  LayerStack[l]++;
      LayerStack[max_copper_layer - 1] = new_index;
    }
  else if (new_index == -1)
    {
      /* Delete the layer at old_index */
      memmove (&PCB->Data->Layer[old_index],
	       &PCB->Data->Layer[old_index + 1],
	       (max_copper_layer + 2 - old_index - 1) * sizeof (LayerType));
      memset (&PCB->Data->Layer[max_copper_layer + 2 - 1], 0, sizeof (LayerType));
      memmove (&group_of_layer[old_index],
	       &group_of_layer[old_index + 1],
	       (max_copper_layer + 2 - old_index - 1) * sizeof (int));
      for (l = 0; l < max_copper_layer; l++)
	if (LayerStack[l] == old_index)
	  memmove (LayerStack + l,
		   LayerStack + l + 1,
		   (max_copper_layer - l - 1) * sizeof (LayerStack[0]));
      max_copper_layer--;
      for (l = 0; l < max_copper_layer; l++)
	if (LayerStack[l] > old_index)
	  LayerStack[l]--;
    }
  else
    {
      /* Move an existing layer */
      memcpy (&saved_layer, &PCB->Data->Layer[old_index], sizeof (LayerType));
      saved_group = group_of_layer[old_index];
      if (old_index < new_index)
	{
	  memmove (&PCB->Data->Layer[old_index],
		   &PCB->Data->Layer[old_index + 1],
		   (new_index - old_index) * sizeof (LayerType));
	  memmove (&group_of_layer[old_index],
		   &group_of_layer[old_index + 1],
		   (new_index - old_index) * sizeof (int));
	}
      else
	{
	  memmove (&PCB->Data->Layer[new_index + 1],
		   &PCB->Data->Layer[new_index],
		   (old_index - new_index) * sizeof (LayerType));
	  memmove (&group_of_layer[new_index + 1],
		   &group_of_layer[new_index],
		   (old_index - new_index) * sizeof (int));
	}
      memcpy (&PCB->Data->Layer[new_index], &saved_layer, sizeof (LayerType));
      group_of_layer[new_index] = saved_group;
    }

  move_all_thermals(old_index, new_index);

  for (g = 0; g < MAX_LAYER; g++)
    PCB->LayerGroups.Number[g] = 0;
  for (l = 0; l < max_copper_layer + 2; l++)
    {
      g = group_of_layer[l];

      /* XXX: Should this ever happen? */
      if (g < 0)
        continue;

      i = PCB->LayerGroups.Number[g]++;
      PCB->LayerGroups.Entries[g][i] = l;
    }

  for (g = 1; g < MAX_LAYER; g++)
    if (PCB->LayerGroups.Number[g - 1] == 0)
      {
	memmove (&PCB->LayerGroups.Number[g - 1],
		 &PCB->LayerGroups.Number[g],
		 (MAX_LAYER - g) * sizeof (PCB->LayerGroups.Number[g]));
	memmove (&PCB->LayerGroups.Entries[g - 1],
		 &PCB->LayerGroups.Entries[g],
		 (MAX_LAYER - g) * sizeof (PCB->LayerGroups.Entries[g]));
      }

  hid_action ("LayersChanged");
  gui->invalidate_all ();
  return 0;
}
Пример #8
0
/*
 *  add an address to an interface.
 */
char*
ipifcadd(Ipifc *ifc, char **argv, int argc, int tentative, Iplifc *lifcp)
{
	int i, type, mtu, sendnbrdisc = 0;
	uint8_t ip[IPaddrlen], mask[IPaddrlen], rem[IPaddrlen];
	uint8_t bcast[IPaddrlen], net[IPaddrlen];
	Iplifc *lifc, **l;
	Fs *f;

	if(ifc->medium == nil)
		return "ipifc not yet bound to device";

	f = ifc->conv->p->f;

	type = Rifc;
	memset(ip, 0, IPaddrlen);
	memset(mask, 0, IPaddrlen);
	memset(rem, 0, IPaddrlen);
	switch(argc){
	case 6:
		if(strcmp(argv[5], "proxy") == 0)
			type |= Rproxy;
		/* fall through */
	case 5:
		mtu = strtoul(argv[4], 0, 0);
		if(mtu >= ifc->medium->mintu && mtu <= ifc->medium->maxtu)
			ifc->maxtu = mtu;
		/* fall through */
	case 4:
		if (parseip(ip, argv[1]) == -1 || parseip(rem, argv[3]) == -1)
			return Ebadip;
		parseipmask(mask, argv[2]);
		maskip(rem, mask, net);
		break;
	case 3:
		if (parseip(ip, argv[1]) == -1)
			return Ebadip;
		parseipmask(mask, argv[2]);
		maskip(ip, mask, rem);
		maskip(rem, mask, net);
		break;
	case 2:
		if (parseip(ip, argv[1]) == -1)
			return Ebadip;
		memmove(mask, defmask(ip), IPaddrlen);
		maskip(ip, mask, rem);
		maskip(rem, mask, net);
		break;
	default:
		return Ebadarg;
	}
	if(isv4(ip))
		tentative = 0;
	wlock(ifc);

	/* ignore if this is already a local address for this ifc */
	for(lifc = ifc->lifc; lifc; lifc = lifc->next) {
		if(ipcmp(lifc->local, ip) == 0) {
			if(lifc->tentative != tentative)
				lifc->tentative = tentative;
			if(lifcp) {
				lifc->onlink = lifcp->onlink;
				lifc->autoflag = lifcp->autoflag;
				lifc->validlt = lifcp->validlt;
				lifc->preflt = lifcp->preflt;
				lifc->origint = lifcp->origint;
			}
			goto out;
		}
	}

	/* add the address to the list of logical ifc's for this ifc */
	lifc = smalloc(sizeof(Iplifc));
	ipmove(lifc->local, ip);
	ipmove(lifc->mask, mask);
	ipmove(lifc->remote, rem);
	ipmove(lifc->net, net);
	lifc->tentative = tentative;
	if(lifcp) {
		lifc->onlink = lifcp->onlink;
		lifc->autoflag = lifcp->autoflag;
		lifc->validlt = lifcp->validlt;
		lifc->preflt = lifcp->preflt;
		lifc->origint = lifcp->origint;
	} else {		/* default values */
		lifc->onlink = lifc->autoflag = 1;
		lifc->validlt = lifc->preflt = ~0L;
		lifc->origint = NOW / 1000;
	}
	lifc->next = nil;

	for(l = &ifc->lifc; *l; l = &(*l)->next)
		;
	*l = lifc;

	/* check for point-to-point interface */
	if(ipcmp(ip, v6loopback)) /* skip v6 loopback, it's a special address */
	if(ipcmp(mask, IPallbits) == 0)
		type |= Rptpt;

	/* add local routes */
	if(isv4(ip))
		v4addroute(f, tifc, rem+IPv4off, mask+IPv4off, rem+IPv4off, type);
	else
		v6addroute(f, tifc, rem, mask, rem, type);

	addselfcache(f, ifc, lifc, ip, Runi);

	if((type & (Rproxy|Rptpt)) == (Rproxy|Rptpt)){
		ipifcregisterproxy(f, ifc, rem);
		goto out;
	}

	if(isv4(ip) || ipcmp(ip, IPnoaddr) == 0) {
		/* add subnet directed broadcast address to the self cache */
		for(i = 0; i < IPaddrlen; i++)
			bcast[i] = (ip[i] & mask[i]) | ~mask[i];
		addselfcache(f, ifc, lifc, bcast, Rbcast);

		/* add subnet directed network address to the self cache */
		for(i = 0; i < IPaddrlen; i++)
			bcast[i] = (ip[i] & mask[i]) & mask[i];
		addselfcache(f, ifc, lifc, bcast, Rbcast);

		/* add network directed broadcast address to the self cache */
		memmove(mask, defmask(ip), IPaddrlen);
		for(i = 0; i < IPaddrlen; i++)
			bcast[i] = (ip[i] & mask[i]) | ~mask[i];
		addselfcache(f, ifc, lifc, bcast, Rbcast);

		/* add network directed network address to the self cache */
		memmove(mask, defmask(ip), IPaddrlen);
		for(i = 0; i < IPaddrlen; i++)
			bcast[i] = (ip[i] & mask[i]) & mask[i];
		addselfcache(f, ifc, lifc, bcast, Rbcast);

		addselfcache(f, ifc, lifc, IPv4bcast, Rbcast);
	}
	else {
		if(ipcmp(ip, v6loopback) == 0) {
			/* add node-local mcast address */
			addselfcache(f, ifc, lifc, v6allnodesN, Rmulti);

			/* add route for all node multicast */
			v6addroute(f, tifc, v6allnodesN, v6allnodesNmask,
				v6allnodesN, Rmulti);
		}

		/* add all nodes multicast address */
		addselfcache(f, ifc, lifc, v6allnodesL, Rmulti);

		/* add route for all nodes multicast */
		v6addroute(f, tifc, v6allnodesL, v6allnodesLmask, v6allnodesL,
			Rmulti);

		/* add solicited-node multicast address */
		ipv62smcast(bcast, ip);
		addselfcache(f, ifc, lifc, bcast, Rmulti);

		sendnbrdisc = 1;
	}

	/* register the address on this network for address resolution */
	if(isv4(ip) && ifc->medium->areg != nil)
		(*ifc->medium->areg)(ifc, ip);

out:
	wunlock(ifc);
	if(tentative && sendnbrdisc)
		icmpns(f, 0, SRC_UNSPEC, ip, TARG_MULTI, ifc->mac);
	return nil;
}
Пример #9
0
Файл: libass.c Проект: etix/vlc
static int BuildRegions( rectangle_t *p_region, int i_max_region, ASS_Image *p_img_list, int i_width, int i_height )
{
    ASS_Image *p_tmp;
    int i_count;

#ifdef DEBUG_REGION
    int64_t i_ck_start = mdate();
#endif

    for( p_tmp = p_img_list, i_count = 0; p_tmp != NULL; p_tmp = p_tmp->next )
        if( p_tmp->w > 0 && p_tmp->h > 0 )
            i_count++;
    if( i_count <= 0 )
        return 0;

    ASS_Image **pp_img = calloc( i_count, sizeof(*pp_img) );
    if( !pp_img )
        return 0;

    for( p_tmp = p_img_list, i_count = 0; p_tmp != NULL; p_tmp = p_tmp->next )
        if( p_tmp->w > 0 && p_tmp->h > 0 )
            pp_img[i_count++] = p_tmp;

    /* */
    const int i_w_inc = __MAX( ( i_width + 49 ) / 50, 32 );
    const int i_h_inc = __MAX( ( i_height + 99 ) / 100, 32 );
    int i_maxh = i_w_inc;
    int i_maxw = i_h_inc;
    int i_region;
    rectangle_t region[i_max_region+1];

    i_region = 0;
    for( int i_used = 0; i_used < i_count; )
    {
        int n;
        for( n = 0; n < i_count; n++ )
        {
            if( pp_img[n] )
                break;
        }
        assert( i_region < i_max_region + 1 );
        region[i_region++] = r_img( pp_img[n] );
        pp_img[n] = NULL; i_used++;

        bool b_ok;
        do {
            b_ok = false;
            for( n = 0; n < i_count; n++ )
            {
                ASS_Image *p_img = pp_img[n];
                if( !p_img )
                    continue;
                rectangle_t r = r_img( p_img );

                int k;
                int i_best = -1;
                int i_best_s = INT_MAX;
                for( k = 0; k < i_region; k++ )
                {
                    if( !r_overlap( &region[k], &r, i_maxw, i_maxh ) )
                        continue;
                    int s = r_surface( &r );
                    if( s < i_best_s )
                    {
                        i_best_s = s;
                        i_best = k;
                    }
                }
                if( i_best >= 0 )
                {
                    r_add( &region[i_best], &r );
                    pp_img[n] = NULL; i_used++;
                    b_ok = true;
                }
            }
        } while( b_ok );

        if( i_region > i_max_region )
        {
            int i_best_i = -1;
            int i_best_j = -1;
            int i_best_ds = INT_MAX;

            /* merge best */
            for( int i = 0; i < i_region; i++ )
            {
                for( int j = i+1; j < i_region; j++ )
                {
                    rectangle_t n = region[i];
                    r_add( &n, &region[j] );
                    int ds = r_surface( &n ) - r_surface( &region[i] ) - r_surface( &region[j] );

                    if( ds < i_best_ds )
                    {
                        i_best_i = i;
                        i_best_j = j;
                        i_best_ds = ds;
                    }
                }
            }
#ifdef DEBUG_REGION
            msg_Err( p_spu, "Merging %d and %d", i_best_i, i_best_j );
#endif
            if( i_best_j >= 0 && i_best_i >= 0 )
            {
                r_add( &region[i_best_i], &region[i_best_j] );

                if( i_best_j+1 < i_region )
                    memmove( &region[i_best_j], &region[i_best_j+1], sizeof(*region) * ( i_region - (i_best_j+1)  ) );
                i_region--;
            }
        }
    }

    /* */
    for( int n = 0; n < i_region; n++ )
        p_region[n] = region[n];

#ifdef DEBUG_REGION
    int64_t i_ck_time = mdate() - i_ck_start;
    msg_Err( p_spu, "ASS: %d objects merged into %d region in %d micros", i_count, i_region, (int)(i_ck_time) );
#endif

    free( pp_img );

    return i_region;
}
Пример #10
0
struct bi_record *
decompress_kernel(unsigned long load_addr, int num_words, unsigned long cksum)
{
#ifdef INTERACTIVE_CONSOLE
	int timer = 0;
	char ch;
#endif
	char *cp;
	struct bi_record *rec;
	unsigned long rec_loc, initrd_loc, TotalMemory = 0;

	serial_fixups();
	com_port = serial_init(0, NULL);

#ifdef CONFIG_LOPEC
	/*
	 * This should work on any board with an MPC10X which is properly
	 * initalized.
	 */
	TotalMemory = mpc10x_get_mem_size(MPC10X_MEM_MAP_B);
#endif

	/* assume the chunk below 8M is free */
	end_avail = (char *)0x00800000;

	/*
	 * Reveal where we were loaded at and where we
	 * were relocated to.
	 */
	puts("loaded at:     "); puthex(load_addr);
	puts(" "); puthex((unsigned long)(load_addr + (4*num_words)));
	puts("\n");
	if ( (unsigned long)load_addr != (unsigned long)&start )
	{
		puts("relocated to:  "); puthex((unsigned long)&start);
		puts(" ");
		puthex((unsigned long)((unsigned long)&start + (4*num_words)));
		puts("\n");
	}

	/*
	 * We link ourself to 0x00800000.  When we run, we relocate
	 * ourselves there.  So we just need __image_begin for the
	 * start. -- Tom
	 */
	zimage_start = (char *)(unsigned long)(&__image_begin);
	zimage_size = (unsigned long)(&__image_end) -
			(unsigned long)(&__image_begin);

	initrd_size = (unsigned long)(&__ramdisk_end) -
		(unsigned long)(&__ramdisk_begin);

	/*
	 * The zImage and initrd will be between start and _end, so they've
	 * already been moved once.  We're good to go now. -- Tom
	 */
	avail_ram = (char *)PAGE_ALIGN((unsigned long)_end);
	puts("zimage at:     "); puthex((unsigned long)zimage_start);
	puts(" "); puthex((unsigned long)(zimage_size+zimage_start));
	puts("\n");

	if ( initrd_size ) {
		puts("initrd at:     ");
		puthex((unsigned long)(&__ramdisk_begin));
		puts(" "); puthex((unsigned long)(&__ramdisk_end));puts("\n");
	}

	avail_ram = (char *)0x00400000;
	end_avail = (char *)0x00800000;
	puts("avail ram:     "); puthex((unsigned long)avail_ram); puts(" ");
	puthex((unsigned long)end_avail); puts("\n");

	if (keyb_present)
		CRT_tstc();  /* Forces keyboard to be initialized */
#ifdef CONFIG_GEMINI
	/*
	 * If cmd_line is empty and cmd_preset is not, copy cmd_preset
	 * to cmd_line.  This way we can override cmd_preset with the
	 * command line from Smon.
	 */

	if ( (cmd_line[0] == '\0') && (cmd_preset[0] != '\0'))
		memcpy (cmd_line, cmd_preset, sizeof(cmd_preset));
#endif

	/* Display standard Linux/PPC boot prompt for kernel args */
	puts("\nLinux/PPC load: ");
	cp = cmd_line;
	memcpy (cmd_line, cmd_preset, sizeof(cmd_preset));
	while ( *cp ) putc(*cp++);

#ifdef INTERACTIVE_CONSOLE
	/*
	 * If they have a console, allow them to edit the command line.
	 * Otherwise, don't bother wasting the five seconds.
	 */
	while (timer++ < 5*1000) {
		if (tstc()) {
			while ((ch = getc()) != '\n' && ch != '\r') {
				/* Test for backspace/delete */
				if (ch == '\b' || ch == '\177') {
					if (cp != cmd_line) {
						cp--;
						puts("\b \b");
					}
				/* Test for ^x/^u (and wipe the line) */
				} else if (ch == '\030' || ch == '\025') {
					while (cp != cmd_line) {
						cp--;
						puts("\b \b");
					}
				} else {
					*cp++ = ch;
					putc(ch);
				}
			}
			break;  /* Exit 'timer' loop */
		}
		udelay(1000);  /* 1 msec */
	}
	*cp = 0;
#endif
	puts("\n");

	puts("Uncompressing Linux...");
	gunzip(0, 0x400000, zimage_start, &zimage_size);
	puts("done.\n");

	/*
	 * Create bi_recs for cmd_line and initrds
	 */
	rec_loc = _ALIGN((unsigned long)(zimage_size) +
			(1 << 20) - 1, (1 << 20));
	rec = (struct bi_record *)rec_loc;

	/* We need to make sure that the initrd and bi_recs do not
	 * overlap. */
	if ( initrd_size ) {
		initrd_loc = (unsigned long)(&__ramdisk_begin);
		/* If the bi_recs are in the middle of the current
		 * initrd, move the initrd to the next MB
		 * boundary. */
		if ((rec_loc > initrd_loc) &&
				((initrd_loc + initrd_size) > rec_loc)) {
			initrd_loc = _ALIGN((unsigned long)(zimage_size)
					+ (2 << 20) - 1, (2 << 20));
		 	memmove((void *)initrd_loc, &__ramdisk_begin,
				 initrd_size);
	         	puts("initrd moved:  "); puthex(initrd_loc);
		 	puts(" "); puthex(initrd_loc + initrd_size);
		 	puts("\n");
		}
	}
 
	rec->tag = BI_FIRST;
	rec->size = sizeof(struct bi_record);
	rec = (struct bi_record *)((unsigned long)rec + rec->size);

	if ( TotalMemory ) {
		rec->tag = BI_MEMSIZE;
		rec->data[0] = TotalMemory;
		rec->size = sizeof(struct bi_record) + sizeof(unsigned long);
		rec = (struct bi_record *)((unsigned long)rec + rec->size);
	}

	rec->tag = BI_CMD_LINE;
	memcpy( (char *)rec->data, cmd_line, strlen(cmd_line)+1);
	rec->size = sizeof(struct bi_record) + strlen(cmd_line) + 1;
	rec = (struct bi_record *)((unsigned long)rec + rec->size);

	if ( initrd_size ) {
		rec->tag = BI_INITRD;
		rec->data[0] = initrd_loc;
		rec->data[1] = initrd_size;
		rec->size = sizeof(struct bi_record) + 2 *
			sizeof(unsigned long);
		rec = (struct bi_record *)((unsigned long)rec +
				rec->size);
	}

	rec->tag = BI_LAST;
	rec->size = sizeof(struct bi_record);
	rec = (struct bi_record *)((unsigned long)rec + rec->size);
	puts("Now booting the kernel\n");
	serial_close(com_port);

	return (struct bi_record *)rec_loc;
}
Пример #11
0
void dbRtreePage::remove_branch(int i)
{
    n -= 1;
    memmove(&b[i], &b[i+1], (n-i)*sizeof(branch));
}
Пример #12
0
static
void copy8(void* dst, const void* src)
{
       memmove(dst, src, 1);
}
Пример #13
0
static
void copy64(void* dst, const void* src)
{
       memmove(dst, src, sizeof(cmsFloat64Number));
}
Пример #14
0
static
void copy16(void* dst, const void* src)
{
       memmove(dst, src, 2);
}
Пример #15
0
void select_model_wind(Point start_pt,unsigned long modifiers)
{
	int						lx,rx,ty,by,sz;
	double					mod_matrix[16],proj_matrix[16],vport[4];
	char					org_vertex_sel[max_model_vertex];
	bool					chg_sel;
	float					*pv;
	Point					pt,last_pt;
	MouseTrackingResult		track;
	
	model_wind_play(FALSE,FALSE);
	
		// get the draw vertexes
		// need to save off array as drawing will reuse
		// array and free it
		
	model_draw_setup_initialize(&model,&draw_setup,TRUE);
		
	draw_model_setup_pose(&model,&draw_setup,cur_pose);
	
	model_create_draw_bones(&model,&draw_setup);
	model_create_draw_vertexes(&model,cur_mesh,&draw_setup);
	
	sz=(model.meshes[cur_mesh].nvertex*3)*sizeof(float);
	pv=(float*)malloc(sz);
	if (pv==NULL) return;
	
	memmove(pv,draw_setup.mesh_arrays[cur_mesh].gl_vertex_array,sz);
		
	model_draw_setup_shutdown(&model,&draw_setup);
	
		// setup transforms
		
	draw_model_gl_setup(&model);
	glGetDoublev(GL_MODELVIEW_MATRIX,mod_matrix);
	glGetDoublev(GL_PROJECTION_MATRIX,proj_matrix);
	glGetIntegerv(GL_VIEWPORT,(GLint*)vport);
	
		// turn on or off?
		
	if ((modifiers&shiftKey)!=0) {
		select_model_wind_save_sel_state(org_vertex_sel);
		SetCCursor(add_cursor);
		chg_sel=TRUE;
	}
	else {
		if ((modifiers&controlKey)!=0) {
			select_model_wind_save_sel_state(org_vertex_sel);
			SetCCursor(sub_cursor);
			chg_sel=FALSE;
		}
		else {
			memset(org_vertex_sel,0x0,max_model_vertex);
			InitCursor();
			chg_sel=TRUE;
		}
	}
	
		// drag the selection

	last_pt.h=last_pt.v=-1;
	
	drag_sel_on=TRUE;
	
	do {
		TrackMouseLocation(NULL,&pt,&track);
		model_wind_offset_click(&pt);
		
		if (memcmp(&last_pt,&pt,sizeof(Point))==0) continue;
		
		memmove(&last_pt,&pt,sizeof(Point));
		
		if (start_pt.h<last_pt.h) {
			lx=start_pt.h;
			rx=last_pt.h;
		}
		else {
			rx=start_pt.h;
			lx=last_pt.h;
		}
		if (start_pt.v<last_pt.v) {
			ty=start_pt.v;
			by=last_pt.v;
		}
		else {
			by=start_pt.v;
			ty=last_pt.v;
		}
		
		select_model_wind_restore_sel_state(org_vertex_sel);
		model_sel_vertex(pv,lx,ty,rx,by,chg_sel,mod_matrix,proj_matrix,vport);
		
		SetRect(&drag_sel_box,lx,ty,rx,by);
		draw_model_wind_pose(&model,cur_mesh,cur_pose);
	
	} while (track!=kMouseTrackingMouseReleased);
	
	drag_sel_on=FALSE;
	
	free(pv);

		// redraw the model
		
	draw_model_wind_pose(&model,cur_mesh,cur_pose);
		
		// reset the data browser
		
	hilite_vertex_rows();

	InitCursor();
}
Пример #16
0
static void console_fb_write_byte(struct console_fb_data_t * dat, unsigned char c)
{
	u32_t cp;
	char * rest;
	int t;

	switch(dat->state)
	{
	case ESC_STATE_NORMAL:
		switch(c)
		{
		case '\e':	/* ESC state */
			dat->state = ESC_STATE_ESC;
			break;

		default:
			dat->utf8[dat->usize++] = c;
			if(utf8_to_ucs4(&cp, 1, (const char *)dat->utf8, dat->usize, (const char **)&rest) > 0)
			{
				dat->usize -= rest - dat->utf8;
				memmove(dat->utf8, rest, dat->usize);
				console_fb_putcode(dat, cp);
			}
			break;
		}
		break;

	case ESC_STATE_ESC:
		switch(c)
		{
		case 'c':	/* Reset */
			console_fb_show_cursor(dat, 1);
			console_fb_set_color_bright(dat, 0);
			console_fb_set_color(dat, TCOLOR_WHITE, TCOLOR_BLACK);
			dat->state = ESC_STATE_NORMAL;
			break;

		case 'D':	/* Scroll display down one line */
			dat->state = ESC_STATE_NORMAL;
			break;

		case 'M':	/* Scroll display up one line */
			dat->state = ESC_STATE_NORMAL;
			break;

		case '7':	/* Save cursor position and attrs */
			console_fb_save_cursor(dat);
			console_fb_save_color(dat);
			dat->state = ESC_STATE_NORMAL;
			break;

		case '8':	/* Restore cursor position and attrs */
			console_fb_restore_cursor(dat);
			console_fb_restore_color(dat);
			dat->state = ESC_STATE_NORMAL;
			break;

		case '[':	/* CSI codes */
			dat->csize = 0;
			dat->abuf[0] = 0;
			dat->asize = 0;
			dat->state = ESC_STATE_CSI;
			break;

		default:
			dat->state = ESC_STATE_NORMAL;
			break;
		}
		break;

	case ESC_STATE_CSI:
		dat->cbuf[dat->csize++] = c;

		switch(dat->cbuf[dat->csize - 1])
		{
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			dat->abuf[dat->asize] *= 10;
			dat->abuf[dat->asize] += (dat->cbuf[dat->csize - 1] - '0');
			break;

		case ';':
			dat->asize++;
			dat->abuf[dat->asize] = 0;
			break;

		case 'A':	/* Move the cursor up */
			t = dat->abuf[0];
			t = (t) ? t : 1;
			console_fb_cursor_gotoxy(dat, dat->x, dat->y - t);
			dat->state = ESC_STATE_NORMAL;
			break;

		case 'B':	/* Move the cursor down */
			t = dat->abuf[0];
			t = (t) ? t : 1;
			console_fb_cursor_gotoxy(dat, dat->x, dat->y + t);
			dat->state = ESC_STATE_NORMAL;
			break;

		case 'C':	/* Move the cursor right */
			t = dat->abuf[0];
			t = (t) ? t : 1;
			console_fb_cursor_gotoxy(dat, dat->x + t, dat->y);
			dat->state = ESC_STATE_NORMAL;
			break;

		case 'D':	/* Move the cursor left */
			t = dat->abuf[0];
			t = (t) ? t : 1;
			console_fb_cursor_gotoxy(dat, dat->x - t, dat->y);
			dat->state = ESC_STATE_NORMAL;
			break;

		case 's':	/* Save cursor position */
			console_fb_save_cursor(dat);
			dat->state = ESC_STATE_NORMAL;
			break;

		case 'u':	/* Restore cursor position */
			console_fb_restore_cursor(dat);
			dat->state = ESC_STATE_NORMAL;
			break;

		case 'J':	/* Clear the screen */
			console_fb_clear_screen(dat);
			dat->state = ESC_STATE_NORMAL;
			break;

		case 'H':	/* Cursor home */
		case 'f':	/* Force cursor position */
			if(dat->asize == 0)
				console_fb_cursor_gotoxy(dat, 0, dat->y);
			else
				console_fb_cursor_gotoxy(dat, dat->abuf[1], dat->abuf[0]);
			dat->state = ESC_STATE_NORMAL;
			break;

		case 'c':		/* Request terminal Type */
			dat->state = ESC_STATE_NORMAL;
			break;

		case 'n':
			switch(dat->abuf[0])
			{
			case 5:		/* Request terminal status */
				break;
			case 6:		/* Request cursor position */
				break;
			};
			dat->state = ESC_STATE_NORMAL;
			break;

		case 'm':		/* Set Display Attributes */
			for(t = 0; t <= dat->asize; t++)
			{
				switch(dat->abuf[t])
				{
				case 0:		/* Reset all attrs */
					console_fb_set_color_bright(dat, 0);
					console_fb_set_color(dat, TCOLOR_WHITE, TCOLOR_BLACK);
					break;
				case 1:		/* Bright */
					console_fb_set_color_bright(dat, 1);
					console_fb_set_color(dat, dat->f, dat->b);
					break;
				case 2:		/* Dim */
					break;
				case 4:		/* Underscore */
					break;
				case 5:		/* Blink */
					break;
				case 7:		/* Reverse */
					console_fb_set_color(dat, dat->b, dat->f);
					break;
				case 8:		/* Hidden */
					break;

				case 30:	/* Set foreground color */
				case 31:
				case 32:
				case 33:
				case 34:
				case 35:
				case 36:
				case 37:
					console_fb_set_color(dat, dat->abuf[t] - 30, dat->b);
					break;

				case 40:	/* Set background color */
				case 41:
				case 42:
				case 43:
				case 44:
				case 45:
				case 46:
				case 47:
					console_fb_set_color(dat, dat->f, dat->abuf[t] - 40);
					break;

				default:
					break;
				}
			}
			dat->state = ESC_STATE_NORMAL;
			break;

		default:
			dat->state = ESC_STATE_NORMAL;
			break;
		}
		break;

	default:
		dat->state = ESC_STATE_NORMAL;
		break;
	}
}
Пример #17
0
bool drag_bone_model_wind(Point start_pt)
{
	int						n,k,drag_handle;
	float					x,y,z,hx,hy,hz,org_ang,org_mov,
							bone_drag_handle_offset;
	float					*ang,*mov;
	Point					pt,last_pt;
	d3vct					vct;
	d3ang					hang,rot;
	model_draw_bone_type	*draw_bone;
	MouseTrackingResult		track;
	
	model_wind_play(FALSE,FALSE);
	
		// setup the draw pose
		
	draw_model_setup_pose(&model,&draw_setup,cur_pose);
	model_create_draw_bones(&model,&draw_setup);
	
		// setup transforms
		
	draw_model_gl_setup(&model);
	
		// click on any drag handles?
		
	drag_handle=drag_handle_none;
	
	if ((cur_pose==-1) || (cur_bone!=-1)) {
	
		draw_bone=&draw_setup.bones[cur_bone];
		
		x=draw_bone->fpnt.x+draw_setup.move.x;
		y=draw_bone->fpnt.y+draw_setup.move.y;
		z=draw_bone->fpnt.z+draw_setup.move.z;
		
		bone_drag_handle_offset=draw_model_bones_drag_handle_offset(&model);

		draw_model_bones_get_handle_rot(&model,&draw_setup,cur_bone,&rot);
		
			// x drag bone

		vct.x=bone_drag_handle_offset;
		vct.y=0;
		vct.z=0;
		hang.x=0;
		hang.y=rot.y;
		hang.z=rot.z;
		draw_model_bones_drag_handle_calc(x,y,z,&vct,&hang,&hx,&hy,&hz);
		if (draw_bone_model_wind_click_box(start_pt,hx,hy,hz)) drag_handle=drag_handle_x;
		
			// y drag bone
			
		vct.x=0;
		vct.y=bone_drag_handle_offset;
		vct.z=0;
		hang.x=rot.x;
		hang.y=0;
		hang.z=rot.z;
		draw_model_bones_drag_handle_calc(x,y,z,&vct,&hang,&hx,&hy,&hz);
		if (draw_bone_model_wind_click_box(start_pt,hx,hy,hz)) drag_handle=drag_handle_y;
		
			// z drag bone
			
		vct.x=0;
		vct.y=0;
		vct.z=bone_drag_handle_offset;
		hang.x=rot.x;
		hang.y=rot.y;
		hang.z=0;
		draw_model_bones_drag_handle_calc(x,y,z,&vct,&hang,&hx,&hy,&hz);
		if (draw_bone_model_wind_click_box(start_pt,hx,hy,hz)) drag_handle=drag_handle_z;
	}
	
		// click on any bones?
		
	if (drag_handle==drag_handle_none) {
	
		k=-1;
		draw_bone=draw_setup.bones;
			
		for (n=0;n!=model.nbone;n++) {
			x=draw_bone->fpnt.x+draw_setup.move.x;
			y=draw_bone->fpnt.y+draw_setup.move.y;
			z=draw_bone->fpnt.z+draw_setup.move.z;
			
			if (draw_bone_model_wind_click_box(start_pt,x,y,z)) {
				k=n;
				break;
			}

			draw_bone++;
		}
		
		if (k==-1) return(FALSE);
	
			// select as current bone
			
		cur_bone=k;
		reset_bone_list();
		draw_model_wind_pose(&model,cur_mesh,cur_pose);

		return(TRUE);
	}
	
		// get drag angle
		
	switch (drag_handle) {
	
		case drag_handle_x:
			ang=&model.poses[cur_pose].bone_moves[cur_bone].rot.x;
			mov=&model.poses[cur_pose].bone_moves[cur_bone].mov.x;
			break;
		
		case drag_handle_y:
			ang=&model.poses[cur_pose].bone_moves[cur_bone].rot.y;
			mov=&model.poses[cur_pose].bone_moves[cur_bone].mov.y;
			break;
			
		case drag_handle_z:
			ang=&model.poses[cur_pose].bone_moves[cur_bone].rot.z;
			mov=&model.poses[cur_pose].bone_moves[cur_bone].mov.z;
			break;
		
		default:
			return(TRUE);
			
	}

	reset_bone_list();
	
		// drag bone

	org_ang=*ang;
	org_mov=*mov;
	last_pt.h=last_pt.v=-1;
	
	undo_set_bone_move(cur_pose,cur_bone);
	
	SetCCursor(bone_drag_cursor);
		
	do {
		TrackMouseLocation(NULL,&pt,&track);
		model_wind_offset_click(&pt);
		
		if (memcmp(&last_pt,&pt,sizeof(Point))==0) continue;
	
		memmove(&last_pt,&pt,sizeof(Point));
		
		x=pt.h-start_pt.h;
		if (x<-180) x=-180;
		if (x>180) x=180;
		
		if (drag_bone_mode==drag_bone_mode_rotate) {
			*ang=org_ang+(((float)x)/2.0f);
		}
		else {
			*mov=org_mov+(((float)x)/20.0f);
		}
		
			// draw the model
			
		model_bone_drag_on=TRUE;
		draw_model_wind_pose(&model,cur_mesh,cur_pose);
		model_bone_drag_on=FALSE;
		
		reset_bone_list();
		redraw_bone_list();

	} while (track!=kMouseTrackingMouseReleased);

	InitCursor();

		// redraw model
		
	draw_model_wind_pose(&model,cur_mesh,cur_pose);

	return(TRUE);
}
Пример #18
0
static int
find_file(int fd, zentry *entry, const char *file_name)
{
    int	    bytes;
    int	    res;
    int	    entry_size;
    int	    read_size;
    int	    base_offset;
    Byte    *p;
    Byte    *bp;
    Byte    *buffer;
    Byte    locbuf[LOCHDR];

    if ((buffer = (Byte*)malloc(BUFSIZE)) == NULL) {
	return(-1);
    }

    p = buffer;
    bp = buffer;

    /*
     * Read the END Header, which is the starting point for ZIP files.
     * (Clearly designed to make writing a zip file easier than reading
     * one. Now isn't that precious...)
     */
    if ((base_offset = find_end(fd, bp)) == -1) {
        free(buffer);
	return (-1);
    }

    /*
     * There is a historical, but undocumented, ability to allow for
     * additional "stuff" to be prepended to the zip/jar file. It seems
     * that this has been used to prepend an actual java launcher
     * executable to the jar on Windows.  Although this is just another
     * form of statically linking a small piece of the JVM to the
     * application, we choose to continue to support it.  Note that no
     * guarantees have been made (or should be made) to the customer that
     * this will continue to work.
     *
     * Therefore, calculate the base offset of the zip file (within the
     * expanded file) by assuming that the central directory is followed
     * immediately by the end record.
     */
    base_offset = base_offset - ENDSIZ(p) - ENDOFF(p);

    /*
     * The END Header indicates the start of the Central Directory
     * Headers. Remember that the desired Central Directory Header (CEN)
     * will almost always be the second one and the first one is a small
     * directory entry ("META-INF/"). Keep the code optimized for
     * that case.
     *
     * Begin by seeking to the beginning of the Central Directory and
     * reading in the first buffer full of bits.
     */
    if (lseek(fd, base_offset + ENDOFF(p), SEEK_SET) < (off_t)0) {
        free(buffer);
	return (-1);
    }
    if ((bytes = read(fd, bp, MINREAD)) < 0) {
        free(buffer);
	return (-1);
    }

    /*
     * Loop through the Central Directory Headers. Note that a valid zip/jar
     * must have an ENDHDR (with ENDSIG) after the Central Directory.
     */
    while (GETSIG(p) == CENSIG) {

	/*
	 * If a complete header isn't in the buffer, shift the contents
	 * of the buffer down and refill the buffer.  Note that the check
	 * for "bytes < CENHDR" must be made before the test for the entire
	 * size of the header, because if bytes is less than CENHDR, the
	 * actual size of the header can't be determined. The addition of
	 * SIGSIZ guarantees that the next signature is also in the buffer
	 * for proper loop termination.
	 */
	if (bytes < CENHDR) {
	    p = memmove(bp, p, bytes);
	    if ((res = read(fd, bp + bytes, MINREAD)) <= 0) {
	      	free(buffer);
		return (-1);
	    }
	    bytes += res;
	}
	entry_size = CENHDR + CENNAM(p) + CENEXT(p) + CENCOM(p);
	if (bytes < entry_size + SIGSIZ) {
	    if (p != bp)
		p = memmove(bp, p, bytes);
	    read_size = entry_size - bytes + SIGSIZ;
	    read_size = (read_size < MINREAD) ? MINREAD : read_size;
	    if ((res = read(fd, bp + bytes,  read_size)) <= 0) {
	      	free(buffer);
		return (-1);
 	    }
	    bytes += res;
	}

	/*
	 * Check if the name is the droid we are looking for; the jar file
	 * manifest.  If so, build the entry record from the data found in
	 * the header located and return success.
	 */
        if (CENNAM(p) == strlen(file_name) &&
          memcmp((p + CENHDR), file_name, strlen(file_name)) == 0) {
	    if (lseek(fd, base_offset + CENOFF(p), SEEK_SET) < (off_t)0) {
    		free(buffer);
		return (-1);
	    }
	    if (read(fd, locbuf, LOCHDR) < 0) {
    		free(buffer);
		return (-1);
	    }
	    if (GETSIG(locbuf) != LOCSIG) {
    		free(buffer);
		return (-1);
	    }
	    entry->isize = CENLEN(p);
	    entry->csize = CENSIZ(p);
	    entry->offset = base_offset + CENOFF(p) + LOCHDR +
		LOCNAM(locbuf) + LOCEXT(locbuf);
	    entry->how = CENHOW(p);
	    free(buffer);
	    return (0);
	}

	/*
	 * Point to the next entry and decrement the count of valid remaining
	 * bytes.
	 */
	bytes -= entry_size;
	p += entry_size;
    }
    free(buffer);
    return (-1);	/* Fell off the end the loop without a Manifest */
}
Пример #19
0
int
lws_tls_openssl_cert_info(X509 *x509, enum lws_tls_cert_info type,
			  union lws_tls_cert_info_results *buf, size_t len)
{
	X509_NAME *xn;
#if !defined(LWS_PLAT_OPTEE)
	char *p;
#endif

	if (!x509)
		return -1;

#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(X509_get_notBefore)
#define X509_get_notBefore(x)	X509_getm_notBefore(x)
#define X509_get_notAfter(x)	X509_getm_notAfter(x)
#endif

	switch (type) {
	case LWS_TLS_CERT_INFO_VALIDITY_FROM:
		buf->time = lws_tls_openssl_asn1time_to_unix(
					X509_get_notBefore(x509));
		if (buf->time == (time_t)-1)
			return -1;
		break;

	case LWS_TLS_CERT_INFO_VALIDITY_TO:
		buf->time = lws_tls_openssl_asn1time_to_unix(
					X509_get_notAfter(x509));
		if (buf->time == (time_t)-1)
			return -1;
		break;

	case LWS_TLS_CERT_INFO_COMMON_NAME:
#if defined(LWS_PLAT_OPTEE)
		return -1;
#else
		xn = X509_get_subject_name(x509);
		if (!xn)
			return -1;
		X509_NAME_oneline(xn, buf->ns.name, (int)len - 2);
		p = strstr(buf->ns.name, "/CN=");
		if (p)
			memmove(buf->ns.name, p + 4, strlen(p + 4) + 1);
		buf->ns.len = (int)strlen(buf->ns.name);
		return 0;
#endif
	case LWS_TLS_CERT_INFO_ISSUER_NAME:
		xn = X509_get_issuer_name(x509);
		if (!xn)
			return -1;
		X509_NAME_oneline(xn, buf->ns.name, (int)len - 1);
		buf->ns.len = (int)strlen(buf->ns.name);
		return 0;

	case LWS_TLS_CERT_INFO_USAGE:
#if defined(LWS_HAVE_X509_get_key_usage)
		buf->usage = X509_get_key_usage(x509);
		break;
#else
		return -1;
#endif

	case LWS_TLS_CERT_INFO_OPAQUE_PUBLIC_KEY:
	{
#ifndef USE_WOLFSSL
		size_t klen = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x509), NULL);
		uint8_t *tmp, *ptmp;

		if (!klen || klen > len)
			return -1;

		tmp = (uint8_t *)OPENSSL_malloc(klen);
		if (!tmp)
			return -1;

		ptmp = tmp;
		if (i2d_X509_PUBKEY(
			      X509_get_X509_PUBKEY(x509), &ptmp) != (int)klen ||
		    !ptmp || lws_ptr_diff(ptmp, tmp) != (int)klen) {
			lwsl_info("%s: cert public key extraction failed\n",
				  __func__);
			if (ptmp)
				OPENSSL_free(tmp);

			return -1;
		}

		buf->ns.len = (int)klen;
		memcpy(buf->ns.name, tmp, klen);
		OPENSSL_free(tmp);
#endif
		return 0;
	}
	default:
		return -1;
	}

	return 0;
}
Пример #20
0
void
ctlwrite(Req *r, Client *c)
{
	char *f[3], *s, *p;
	int nf;

	s = emalloc(r->ifcall.count+1);
	memmove(s, r->ifcall.data, r->ifcall.count);
	s[r->ifcall.count] = '\0';

	f[0] = s;
	p = strchr(s, ' ');
	if(p == nil)
		nf = 1;
	else{
		*p++ = '\0';
		f[1] = p;
		nf = 2;
	}

	if(f[0][0] == '\0'){
		free(s);
		respond(r, nil);
		return;
	}

	r->ofcall.count = r->ifcall.count;
	if(strcmp(f[0], "hangup") == 0){
		if(c->pid == 0){
			respond(r, "connection already hung up");
			goto Out;
		}
		postnote(PNPROC, c->pid, "kill");
		respond(r, nil);
		goto Out;
	}

	if(strcmp(f[0], "connect") == 0){
		if(c->cmd != nocmd){
			respond(r, "already have connection");
			goto Out;
		}
		if(nf == 1){
			respond(r, "need argument to connect");
			goto Out;
		}
		c->status = Exec;
		if(p = strrchr(f[1], '!'))
			*p = '\0';
		c->cmd = emalloc(4+1+strlen(f[1])+1);
		strcpy(c->cmd, "exec ");
		strcat(c->cmd, f[1]);
		c->execreq = r;
		threadcreate(execthread, c, STACK);
		goto Out;
	}

	respond(r, "bad or inappropriate control message");
Out:
	free(s);
}
Пример #21
0
char *
canonicalize_filename_mode (const char *name, canonicalize_mode_t can_mode)
{
  char *rname, *dest, *extra_buf = NULL;
  char const *start;
  char const *end;
  char const *rname_limit;
  size_t extra_len = 0;
  Hash_table *ht = NULL;
  int saved_errno;
  int can_flags = can_mode & ~CAN_MODE_MASK;
  bool logical = can_flags & CAN_NOLINKS;
  size_t prefix_len;

  can_mode &= CAN_MODE_MASK;

  if (MULTIPLE_BITS_SET (can_mode))
    {
      errno = EINVAL;
      return NULL;
    }

  if (name == NULL)
    {
      errno = EINVAL;
      return NULL;
    }

  if (name[0] == '\0')
    {
      errno = ENOENT;
      return NULL;
    }

  /* This is always zero for Posix hosts, but can be 2 for MS-Windows
     and MS-DOS X:/foo/bar file names.  */
  prefix_len = FILE_SYSTEM_PREFIX_LEN (name);

  if (!IS_ABSOLUTE_FILE_NAME (name))
    {
      rname = xgetcwd ();
      if (!rname)
        return NULL;
      dest = strchr (rname, '\0');
      if (dest - rname < PATH_MAX)
        {
          char *p = xrealloc (rname, PATH_MAX);
          dest = p + (dest - rname);
          rname = p;
          rname_limit = rname + PATH_MAX;
        }
      else
        {
          rname_limit = dest;
        }
      start = name;
      prefix_len = FILE_SYSTEM_PREFIX_LEN (rname);
    }
  else
    {
      rname = xmalloc (PATH_MAX);
      rname_limit = rname + PATH_MAX;
      dest = rname;
      if (prefix_len)
        {
          memcpy (rname, name, prefix_len);
          dest += prefix_len;
        }
      *dest++ = '/';
      if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
        {
          if (ISSLASH (name[1]) && !ISSLASH (name[2]) && !prefix_len)
            *dest++ = '/';
          *dest = '\0';
        }
      start = name + prefix_len;
    }

  for ( ; *start; start = end)
    {
      /* Skip sequence of multiple file name separators.  */
      while (ISSLASH (*start))
        ++start;

      /* Find end of component.  */
      for (end = start; *end && !ISSLASH (*end); ++end)
        /* Nothing.  */;

      if (end - start == 0)
        break;
      else if (end - start == 1 && start[0] == '.')
        /* nothing */;
      else if (end - start == 2 && start[0] == '.' && start[1] == '.')
        {
          /* Back up to previous component, ignore if at root already.  */
          if (dest > rname + prefix_len + 1)
            for (--dest; dest > rname && !ISSLASH (dest[-1]); --dest)
              continue;
          if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
              && !prefix_len && ISSLASH (*dest) && !ISSLASH (dest[1]))
            dest++;
        }
      else
        {
          struct stat st;

          if (!ISSLASH (dest[-1]))
            *dest++ = '/';

          if (dest + (end - start) >= rname_limit)
            {
              ptrdiff_t dest_offset = dest - rname;
              size_t new_size = rname_limit - rname;

              if (end - start + 1 > PATH_MAX)
                new_size += end - start + 1;
              else
                new_size += PATH_MAX;
              rname = xrealloc (rname, new_size);
              rname_limit = rname + new_size;

              dest = rname + dest_offset;
            }

          dest = memcpy (dest, start, end - start);
          dest += end - start;
          *dest = '\0';

          if (logical && (can_mode == CAN_MISSING))
            {
              /* Avoid the stat in this case as it's inconsequential.
                 i.e. we're neither resolving symlinks or testing
                 component existence.  */
              st.st_mode = 0;
            }
          else if ((logical ? stat (rname, &st) : lstat (rname, &st)) != 0)
            {
              saved_errno = errno;
              if (can_mode == CAN_EXISTING)
                goto error;
              if (can_mode == CAN_ALL_BUT_LAST)
                {
                  if (end[strspn (end, SLASHES)] || saved_errno != ENOENT)
                    goto error;
                  continue;
                }
              st.st_mode = 0;
            }

          if (S_ISLNK (st.st_mode))
            {
              char *buf;
              size_t n, len;

              /* Detect loops.  We cannot use the cycle-check module here,
                 since it's actually possible to encounter the same symlink
                 more than once in a given traversal.  However, encountering
                 the same symlink,NAME pair twice does indicate a loop.  */
              if (seen_triple (&ht, name, &st))
                {
                  if (can_mode == CAN_MISSING)
                    continue;
                  saved_errno = ELOOP;
                  goto error;
                }

              buf = areadlink_with_size (rname, st.st_size);
              if (!buf)
                {
                  if (can_mode == CAN_MISSING && errno != ENOMEM)
                    continue;
                  saved_errno = errno;
                  goto error;
                }

              n = strlen (buf);
              len = strlen (end);

              if (!extra_len)
                {
                  extra_len =
                    ((n + len + 1) > PATH_MAX) ? (n + len + 1) : PATH_MAX;
                  extra_buf = xmalloc (extra_len);
                }
              else if ((n + len + 1) > extra_len)
                {
                  extra_len = n + len + 1;
                  extra_buf = xrealloc (extra_buf, extra_len);
                }

              /* Careful here, end may be a pointer into extra_buf... */
              memmove (&extra_buf[n], end, len + 1);
              name = end = memcpy (extra_buf, buf, n);

              if (IS_ABSOLUTE_FILE_NAME (buf))
                {
                  size_t pfxlen = FILE_SYSTEM_PREFIX_LEN (buf);

                  if (pfxlen)
                    memcpy (rname, buf, pfxlen);
                  dest = rname + pfxlen;
                  *dest++ = '/'; /* It's an absolute symlink */
                  if (DOUBLE_SLASH_IS_DISTINCT_ROOT)
                    {
                      if (ISSLASH (buf[1]) && !ISSLASH (buf[2]) && !pfxlen)
                        *dest++ = '/';
                      *dest = '\0';
                    }
                  /* Install the new prefix to be in effect hereafter.  */
                  prefix_len = pfxlen;
                }
              else
                {
                  /* Back up to previous component, ignore if at root
                     already: */
                  if (dest > rname + prefix_len + 1)
                    for (--dest; dest > rname && !ISSLASH (dest[-1]); --dest)
                      continue;
                  if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1
                      && ISSLASH (*dest) && !ISSLASH (dest[1]) && !prefix_len)
                    dest++;
                }

              free (buf);
            }
          else
            {
              if (!S_ISDIR (st.st_mode) && *end && (can_mode != CAN_MISSING))
                {
                  saved_errno = ENOTDIR;
                  goto error;
                }
            }
        }
    }
  if (dest > rname + prefix_len + 1 && ISSLASH (dest[-1]))
    --dest;
  if (DOUBLE_SLASH_IS_DISTINCT_ROOT && dest == rname + 1 && !prefix_len
      && ISSLASH (*dest) && !ISSLASH (dest[1]))
    dest++;
  *dest = '\0';
  if (rname_limit != dest + 1)
    rname = xrealloc (rname, dest - rname + 1);

  free (extra_buf);
  if (ht)
    hash_free (ht);
  return rname;

error:
  free (extra_buf);
  free (rname);
  if (ht)
    hash_free (ht);
  errno = saved_errno;
  return NULL;
}
Пример #22
0
// returns qtrue while still playing normally, else qfalse for either finished or request-offset-error
//
qboolean MP3Stream_GetSamples( channel_t *ch, int startingSampleNum, int count, short *buf, qboolean bStereo )
{
	qboolean qbStreamStillGoing = qtrue;

	const int iQuarterOfSlidingBuffer		=  sizeof(ch->MP3SlidingDecodeBuffer)/4;
	const int iThreeQuartersOfSlidingBuffer	= (sizeof(ch->MP3SlidingDecodeBuffer)*3)/4;

//	Com_Printf("startingSampleNum %d\n",startingSampleNum);

	count *= 2/* <- = SOF2; ch->sfx->width*/;	// count arg was for words, so double it for bytes;

	// convert sample number into a byte offset... (make new variable for clarity?)
	//
	startingSampleNum *= 2 /* <- = SOF2; ch->sfx->width*/ * (bStereo?2:1);

	if ( startingSampleNum < ch->iMP3SlidingDecodeWindowPos)
	{
		// what?!?!?!   smegging time travel needed or something?, forget it
		memset(buf,0,count);
		return qfalse;
	}

//	Com_OPrintf("\nRequest: startingSampleNum %d, count %d\n",startingSampleNum,count);
//	Com_OPrintf("WindowPos %d, WindowWritePos %d\n",ch->iMP3SlidingDecodeWindowPos,ch->iMP3SlidingDecodeWritePos);

//	qboolean _bDecoded = qfalse;

	while (!
		(
			(startingSampleNum			>= ch->iMP3SlidingDecodeWindowPos)
			&&
			(startingSampleNum + count	<  ch->iMP3SlidingDecodeWindowPos + ch->iMP3SlidingDecodeWritePos)
			)
			)
	{
//		if (!_bDecoded)
//		{
//			Com_Printf(S_COLOR_YELLOW"Decode needed!\n");
//		}
//		_bDecoded = qtrue;
//		Com_OPrintf("Scrolling...");

		int _iBytesDecoded = MP3Stream_Decode( (LP_MP3STREAM) &ch->MP3StreamHeader, bStereo );	// stereo only for music, so this is safe
//		Com_OPrintf("%d bytes decoded\n",_iBytesDecoded);
		if (_iBytesDecoded == 0)
		{
			// no more source data left so clear the remainder of the buffer...
			//
			memset(ch->MP3SlidingDecodeBuffer + ch->iMP3SlidingDecodeWritePos, 0, sizeof(ch->MP3SlidingDecodeBuffer)-ch->iMP3SlidingDecodeWritePos);
//			Com_OPrintf("Finished\n");
			qbStreamStillGoing = qfalse;
			break;
		}
		else
		{
			memcpy(ch->MP3SlidingDecodeBuffer + ch->iMP3SlidingDecodeWritePos,ch->MP3StreamHeader.bDecodeBuffer,_iBytesDecoded);

			ch->iMP3SlidingDecodeWritePos += _iBytesDecoded;

			// if reached 3/4 of buffer pos, backscroll the decode window by one quarter...
			//
			if (ch->iMP3SlidingDecodeWritePos > iThreeQuartersOfSlidingBuffer)
			{
				memmove(ch->MP3SlidingDecodeBuffer, ((byte *)ch->MP3SlidingDecodeBuffer + iQuarterOfSlidingBuffer), iThreeQuartersOfSlidingBuffer);
				ch->iMP3SlidingDecodeWritePos -= iQuarterOfSlidingBuffer;
				ch->iMP3SlidingDecodeWindowPos+= iQuarterOfSlidingBuffer;
			}
		}
//		Com_OPrintf("WindowPos %d, WindowWritePos %d\n",ch->iMP3SlidingDecodeWindowPos,ch->iMP3SlidingDecodeWritePos);
	}

//	if (!_bDecoded)
//	{
//		Com_Printf(S_COLOR_YELLOW"No decode needed\n");
//	}

	assert(startingSampleNum >= ch->iMP3SlidingDecodeWindowPos);
	memcpy( buf, ch->MP3SlidingDecodeBuffer + (startingSampleNum-ch->iMP3SlidingDecodeWindowPos), count);

//	Com_OPrintf("OK\n\n");

	return qbStreamStillGoing;
}
Пример #23
0
long tcp_connect_socks_proxy(bmdnet_handler_ptr handler,char *host,long port)
{
	long status;

	if( handler == NULL ) { BMD_FOK(BMD_ERR_PARAM1);};
	if( host == NULL ) { BMD_FOK(BMD_ERR_PARAM2);};

	status=tcp_connect(handler,handler->proxy_adr,handler->proxy_port);
	if( status != BMD_OK )
	{
		PRINT_ERROR("Failed to connect with proxy at %s:%li\n",handler->proxy_adr,handler->proxy_port);
		BMD_FOK(BMD_ERR_NET_CONNECT);
	}

	if( handler->proxy_type == BMDNET_PROXY_SOCKS4 )
	{
		socks4_request_t request_header;
		char complete_request[1024];
		char *buffer=NULL;
		long response_code			= 0;
		long length				= 0;
		long request_header_size		= 0;

		memset(complete_request,0,256);
		request_header.version=4;
		request_header.command=1;
		request_header.destport=htons((u_short)port);
		request_header.destaddr=inet_addr(host);
		request_header_size=sizeof(request_header);
		memmove(complete_request,(char *)(&request_header),request_header_size);
		if(handler->proxy_user)
		{
			length=(long)strlen((char *)handler->proxy_user);
			memmove(complete_request+request_header_size,(char *)handler->proxy_user,length);
			bmdnet_send(handler, complete_request,length+request_header_size+1);
		}
		else
		{
			bmdnet_send(handler,complete_request,request_header_size+1);
		}
		buffer=(char *)malloc(10000);
		memset(buffer,0,10000);
		bmdnet_recv(handler,buffer,1024);
		if((long)buffer[0]==0)
		{
			response_code=(long)buffer[1];
			switch(response_code)
			{
				case 90:
					return 0;
				case 91:
					return -1;
				case 92:
					return -2;
				case 93:
					return -3;
			}
		}
		else
		{
			return -1;
		}
	}
	else
	if( handler->proxy_type == BMDNET_PROXY_SOCKS4A )
	{
		socks4a_request_t request_header;
		char complete_request[1024];
		char *buffer=NULL;
		long response_code			= 0;
		long length				= 0;
		long request_header_size		= 0;

		memset(complete_request,0,256);
		request_header.version=4;
		request_header.command=1;
		request_header.destport=htons((u_short)port);
		request_header.destaddr=inet_addr("0.0.0.1");
		request_header_size=sizeof(request_header);
		memmove(complete_request,(char *)(&request_header),request_header_size);
		if(handler->proxy_user)
		{
			length=(long)strlen((char *)handler->proxy_user);
			memmove(complete_request+request_header_size,(char *)handler->proxy_user,length);
			memmove(complete_request+request_header_size+length+1,host,strlen(host));
			bmdnet_send(handler, complete_request,length+request_header_size+(long)strlen(host)+2);
		}
		else
		{
			memmove(complete_request+request_header_size+1,host,strlen(host));
			bmdnet_send(handler,complete_request,request_header_size+(long)strlen(host)+2);
		}
		buffer=(char *)malloc(10000);
		memset(buffer,0,10000);
		bmdnet_recv(handler,buffer,1024);
		if((long)buffer[0]==0)
		{
			response_code=(long)buffer[1];
			switch(response_code) 
			{
				case 90:
					return 0;
				case 91:
					return -1;
				case 92:
					return -2;
				case 93:
					return -3;
			}
		}
		else
		{
			return -1;
		}
	}
	else
	if( handler->proxy_type == BMDNET_PROXY_SOCKS5 )
	{
		long i;
		long ip_flag					= 1;
		char *buffer					= NULL;
		socks5_init_request_t init_request_header;
		socks5_request_t request_header;
		char complete_request[1024];
		char initial_request[1024];
		__int32 tmp1;
		__int16 tmp2;

		/* wysylanie inicjalnego requesta z deklaracja metod */
		memset(initial_request,0,1024);init_request_header.version=0x05;init_request_header.nmethod=1;
		memmove(initial_request,(char *)(&init_request_header),sizeof(init_request_header));
		if(handler->proxy_auth_type == BMDNET_PROXY_AUTH_BASIC )
		{
			initial_request[sizeof(init_request_header)]=0x02;
		}
		BMD_FOK_CHG(bmdnet_send(handler,initial_request,sizeof(init_request_header)+1), -1);
	
		buffer=(char *)malloc(1024);
		memset(buffer,0,1024);
	
		BMD_FOK_CHG(bmdnet_recv(handler,buffer,1023),-1);
	
		if( ((unsigned char)buffer[1]) == 0xFF) /* zadna metoda autoryzacji nie jest wspierana - patrz RFC */
		{
			BMD_FOK(-1);
		}
	
		free(buffer);buffer=NULL;

		/* faza autoryzacji user/password */
		if(handler->proxy_auth_type == BMDNET_PROXY_AUTH_BASIC )
		{
			buffer=(char *)malloc(1024);
			memset(buffer,0,1024);
			buffer[0]=0x01;buffer[1]=(char)strlen((char *)handler->proxy_user);
			memmove(buffer+2,handler->proxy_user,strlen(handler->proxy_user));
			buffer[2+strlen(handler->proxy_user)]=(char)strlen((char *)handler->proxy_pass);
			memmove(buffer+3+strlen((char *)handler->proxy_user),(char *)handler->proxy_pass,
				strlen((char *)handler->proxy_pass));
			BMD_FOK_CHG(bmdnet_send(handler,buffer,(long)strlen(buffer)),-1);

			memset(buffer,0,1024);
			BMD_FOK_CHG(bmdnet_recv(handler,buffer,1023),-1);
	
			if(buffer[1]!=0x00)
			{
				BMD_FOK(-1);
			}
		}
		memset(complete_request,0,256);
		request_header.ver=0x05;request_header.cmd=1;request_header.rsv=0x00;
		for(i=0;i<(long)strlen(host);i++)
		{
			if(isalpha(host[i])) /* jesli wystapi jakas litera uznaje ze to adres domenowy */
			{
				ip_flag=0;
				break;
			}
		}
		if(ip_flag==1)
		{
			request_header.atyp=0x01; /* to jest IP */
		}
		else
		{
			request_header.atyp=0x03; /* to jest domena */
		}
		memmove(complete_request,(char *)(&request_header),sizeof(request_header));
		if(ip_flag==1)
		{
			tmp1=inet_addr(host);
		}
		tmp2=htons((u_short)port);
		if(ip_flag==1)
		{
			memmove(complete_request+sizeof(request_header),&tmp1,4);
			memmove(complete_request+sizeof(request_header)+4,&tmp2,2);
			status=bmdnet_send(handler,complete_request,sizeof(request_header)+6);
			if( status < 0 )
			{
				return -1;
			}
		}
		else
		{
			char *tmp=NULL;
			tmp=(char *)malloc(strlen(host)+3);
			tmp[0]=(char)strlen(host);
			memmove(tmp+1,host,strlen(host));
			memmove(complete_request+sizeof(request_header),tmp,strlen(host)+1);
			memmove(complete_request+sizeof(request_header)+strlen(host)+1,&tmp2,2);
			BMD_FOK_CHG(bmdnet_send(handler,complete_request,sizeof(request_header)+ 
			(long)strlen(host)+3),-1);
			free(tmp);tmp=NULL;
		}
		buffer=(char *)malloc(1024);
		memset(buffer,0,1024);
		BMD_FOK_CHG(bmdnet_recv(handler,buffer,1023),-1);
	
		if(buffer[1]==0x00) /* OK*/
			return 0;
		/* jakis blad - nie interesuje nas jaki */
		return -1;
	}
	else
	{
		PRINT_ERROR("Unsupported proxy_type\n");
		BMD_FOK(BMD_ERR_UNIMPLEMENTED);
	}

	return BMD_OK;
}
Пример #24
0
char* VSIArchiveFilesystemHandler::SplitFilename(const char *pszFilename,
                                                 CPLString &osFileInArchive,
                                                 int bCheckMainFileExists)
{
    int i = 0;

    if (strcmp(pszFilename, GetPrefix()) == 0)
        return NULL;

    /* Allow natural chaining of VSI drivers without requiring double slash */
    
    CPLString osDoubleVsi(GetPrefix());
    osDoubleVsi += "/vsi";
    
    if (strncmp(pszFilename, osDoubleVsi.c_str(), osDoubleVsi.size()) == 0)
        pszFilename += strlen(GetPrefix());
    else
        pszFilename += strlen(GetPrefix()) + 1;

    while(pszFilename[i])
    {
        std::vector<CPLString> oExtensions = GetExtensions();
        std::vector<CPLString>::const_iterator iter;
        int nToSkip = 0;

        for( iter = oExtensions.begin(); iter != oExtensions.end(); ++iter )
        {
            const CPLString& osExtension = *iter;
            if (EQUALN(pszFilename + i, osExtension.c_str(), strlen(osExtension.c_str())))
            {
                nToSkip = strlen(osExtension.c_str());
                break;
            }
        }

        if (nToSkip != 0)
        {
            VSIStatBufL statBuf;
            char* archiveFilename = CPLStrdup(pszFilename);
            int bArchiveFileExists = FALSE;

            if (archiveFilename[i + nToSkip] == '/' ||
                archiveFilename[i + nToSkip] == '\\')
            {
                archiveFilename[i + nToSkip] = 0;
            }

            if (!bCheckMainFileExists)
            {
                bArchiveFileExists = TRUE;
            }
            else
            {
                CPLMutexHolder oHolder( &hMutex );

                if (oFileList.find(archiveFilename) != oFileList.end() )
                {
                    bArchiveFileExists = TRUE;
                }
            }

            if (!bArchiveFileExists)
            {
                VSIFilesystemHandler *poFSHandler = 
                    VSIFileManager::GetHandler( archiveFilename );
                if (poFSHandler->Stat(archiveFilename, &statBuf,
                                      VSI_STAT_EXISTS_FLAG | VSI_STAT_NATURE_FLAG) == 0 &&
                    !VSI_ISDIR(statBuf.st_mode))
                {
                    bArchiveFileExists = TRUE;
                }
            }

            if (bArchiveFileExists)
            {
                if (pszFilename[i + nToSkip] == '/' ||
                    pszFilename[i + nToSkip] == '\\')
                {
                    char* pszArchiveInFileName = CPLStrdup(pszFilename + i + nToSkip + 1);

                    /* Replace a/../b by b and foo/a/../b by foo/b */
                    while(TRUE)
                    {
                        char* pszPrevDir = strstr(pszArchiveInFileName, "/../");
                        if (pszPrevDir == NULL || pszPrevDir == pszArchiveInFileName)
                            break;

                        char* pszPrevSlash = pszPrevDir - 1;
                        while(pszPrevSlash != pszArchiveInFileName &&
                                *pszPrevSlash != '/')
                            pszPrevSlash --;
                        if (pszPrevSlash == pszArchiveInFileName)
                            memmove(pszArchiveInFileName, pszPrevDir + nToSkip, strlen(pszPrevDir + nToSkip) + 1);
                        else
                            memmove(pszPrevSlash + 1, pszPrevDir + nToSkip, strlen(pszPrevDir + nToSkip) + 1);
                    }

                    osFileInArchive = pszArchiveInFileName;
                    CPLFree(pszArchiveInFileName);
                }
                else
                    osFileInArchive = "";

                /* Remove trailing slash */
                if (strlen(osFileInArchive))
                {
                    char lastC = osFileInArchive[strlen(osFileInArchive) - 1];
                    if (lastC == '\\' || lastC == '/')
                        osFileInArchive[strlen(osFileInArchive) - 1] = 0;
                }

                return archiveFilename;
            }
            CPLFree(archiveFilename);
        }
        i++;
    }
    return NULL;
}
Пример #25
0
// Analyze FTP server response and take some action
// Server response is in recvBuf
//--------------------------
static void response( void )
{
  if (!(status & FTP_CONNECTED)) return;
  if (recvBuf == NULL) return;

  uint16_t cmd = 0;
  
  if (*(recvBuf+3) != ' ') {
    _setResponse(cmd);
    return;
  }
  *(recvBuf+3) = '\0';
  cmd = atoi(recvBuf);
  if (cmd == 0) {
    _setResponse(cmd);
    return;
  }
  recvLen -= 4;
  memmove(recvBuf, (recvBuf+4), recvLen);
  *(recvBuf+recvLen) = '\0';
  
  
  if (cmd == 220) {
    ftp_log("[FTP cmd] Send user: %s\r\n",ftpuser);
    char tmps[100];
    sprintf(tmps,"USER %s\r\n",ftpuser);
    _send(&tmps[0], strlen(ftpuser)+7);
  }
  else if (cmd == 331) {
    ftp_log("[FTP cmd] Send pass: %s\r\n",ftppass);
    char tmps[100];
    sprintf(tmps,"PASS %s\r\n", ftppass);
    _send(&tmps[0], strlen(ftppass)+7);
  }
  else if (cmd == 230) {
    if (ftppass != NULL) {
      free(ftppass);
      ftppass = NULL;
    }
    if (ftpuser != NULL) {
      free(ftpuser);
      ftpuser = NULL;
    }
    _send("TYPE I\r\n", 8);

    ftp_log("[FTP cmd] Login OK.\r\n");
    status |= FTP_LOGGED;
    ftpCmdSocket->clientFlag = REQ_ACTION_LOGGED;
  }
  else if (cmd == 530) {
    ftp_log("[FTP cmd] Login authentication failed\r\n");
    ftpCmdSocket->clientFlag = REQ_ACTION_QUIT;
  }
  else if (cmd == 221) {
    ftp_log("[FTP cmd] Request Logout\r\n");
    ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
  }
  else if (cmd == 226) {
    // Closing data connection
    _setResponse(cmd);
  }
  else if (cmd == 250) {
    // Requested file action okay, completed
    _setResponse(cmd);
  }
  else if (cmd == 257) {
    // Pathname
    _setResponse(cmd);
    if (ftpresponse != NULL) {
      uint16_t i;
      for (i = 0; i<strlen(ftpresponse); i++) {
        if (*(recvBuf+i) == '"') break;
      }
      if (i<strlen(ftpresponse)) {
        memmove(ftpresponse, ftpresponse+i+1, strlen(ftpresponse)-i);
        for (i=strlen(ftpresponse)-1; i>0; i--) {
          if (*(ftpresponse+i) == '"') *(ftpresponse+i) = '\0';
        }
      }
    }
  }
  else if ((cmd == 150) || (cmd == 125)) {
    // mark: Accepted data connection
    if ((ftpfile != NULL) && ftpDataSocket != NULL) {
      status |= FTP_SENDING;
      if ((send_type & SEND_STRING)) {
        ftp_log("[FTP dta] Sending string to %s (%d)\r\n", ftpfile, file_size);
      }
      else {
        ftp_log("[FTP dta] Sending file %s (%d)\r\n", ftpfile, file_size);
      }
    }
    else _setResponse(cmd);
  }
  else if (cmd == 227) {
    // entering passive mod
    char *tStr = strtok(recvBuf, "(,");
    uint8_t array_pasv[6];
    for ( int i = 0; i < 6; i++) {
      tStr = strtok(NULL, "(,");
      if (tStr != NULL) {
        array_pasv[i] = atoi(tStr);
      }
      else {
        array_pasv[i] = 0;
      }
    }
    uint32_t dataPort, dataServ;
    dataPort = (uint32_t)((array_pasv[4] << 8) + (array_pasv[5] & 255));
    dataServ = (uint32_t)((array_pasv[0] << 24) + (array_pasv[1] << 16) + (array_pasv[2] << 8) + (array_pasv[3] & 255));

    if ((dataServ != 0) && (dataPort != 0)) {
      // connect data socket
      if (_openDataSocket() >= 0) {
        ftpDataSocket->addr.s_ip = dataServ;
        ftpDataSocket->addr.s_port = dataPort;

        char ip[17]; memset(ip, 0x00, 17);
        inet_ntoa(ip, ftpDataSocket->addr.s_ip);
        ftp_log("[FTP dta] Opening data connection to: %s:%d\r\n", ip, ftpDataSocket->addr.s_port);

        struct sockaddr_t *paddr = &(ftpDataSocket->addr);
        int slen = sizeof(ftpDataSocket->addr);
      
        //_micoNotify will be called if connected
        int stat = connect(ftpDataSocket->socket, paddr, slen);
        if (stat < 0) {
          ftp_log("[FTP dta] Data connection error: %d\r\n", stat);
          ftpCmdSocket->clientFlag = NO_ACTION;
          ftpCmdSocket->clientLastFlag = NO_ACTION;
          data_done = 1;
          file_status = -9;
          closeDataSocket();
        }
        else {
          // Data socket connected, initialize action
          if (ftpCmdSocket->clientLastFlag == REQ_ACTION_LIST) {
            ftpCmdSocket->clientLastFlag = NO_ACTION;
            ftpCmdSocket->clientFlag = REQ_ACTION_DOLIST;
          }
          else if (ftpCmdSocket->clientLastFlag == REQ_ACTION_RECV) {
            ftpCmdSocket->clientLastFlag = NO_ACTION;
            ftpCmdSocket->clientFlag = REQ_ACTION_DORECV;
          }
          else if (ftpCmdSocket->clientLastFlag == REQ_ACTION_SEND) {
            ftpCmdSocket->clientLastFlag = NO_ACTION;
            ftpCmdSocket->clientFlag = REQ_ACTION_DOSEND;
          }
        }
      }
    }
    else {
      ftp_log("[FTP dta] Wrong pasv address:port received!\r\n");
      ftpCmdSocket->clientFlag = REQ_ACTION_DISCONNECT;
    }
  }
  else _setResponse(cmd);
}
Пример #26
0
void Blob2D::resize(short destLeft, short destTop, short destWidth, short destHeight)
{
	if( width == 0 && height == 0)
	{
		size_t siz = Bitmap::size(destWidth,destHeight);
		if( alloc_size < siz )
		{
			if(ptr)
				mem_del(ptr);
			ptr = (Bitmap *)mem_add((alloc_size = siz + DEFAULT_BLOB2D_INC));
		}
		memset(ptr, BACKGROUND_COLOR, siz);
		ptr->init(destWidth, destHeight);
	}
	else if( destWidth == 0 && destHeight == 0 )
	{
		err_when(!ptr);
		ptr->init(destWidth, destHeight);
	}
	else if( left_edge == destLeft && top_edge == destTop && width == destWidth )
	{
		if( destHeight == height )
			return;		// unchange

		size_t siz = Bitmap::size(destWidth,destHeight);
		if( alloc_size < siz )
		{
			ptr = (Bitmap *)mem_resize(ptr, (alloc_size = siz + DEFAULT_BLOB2D_INC));
		}

		if( destHeight > height && destWidth > 0 )
		{
			int y2 = top_edge+height;	// must keep the old instant
			height = destHeight;			// as height must be change to make fill_area correct

			// extend, then fill the new with the background color
			fill_area(destLeft, top_edge+height, destLeft+destWidth-1, destTop+destHeight-1, BACKGROUND_COLOR, 0);
		}
	}
	else if( left_edge <= destLeft && top_edge <= destTop &&
		left_edge+width >= destLeft+destWidth && top_edge+height >= destTop+destHeight)
	{
		// clipping
		unsigned char *src = ptr->get_ptr(destLeft-left_edge, destTop-top_edge);
		int srcPitch = ptr->get_pitch();
		ptr->init(destWidth, destHeight);
		unsigned char *dest = ptr->get_ptr();
		int destPitch = ptr->get_pitch();

		for(int y = 0; y < destHeight; ++y, src += srcPitch, dest += destPitch )
			memmove(dest, src, destWidth);

		// ptr = (Bitmap *)mem_resize(ptr, ptr->size());
	}
	else
	{
		// general resize, new another buffer
		// copy range, intersection of two area :
		short copyLeft, copyTop, copyWidth, copyHeight;
		copyLeft = MAX(destLeft, left_edge);
		copyTop = MAX(destTop, top_edge);
		copyWidth = MIN(destLeft + destWidth, left_edge + width) - copyLeft;
		copyHeight = MIN(destTop + destHeight, top_edge + height) - copyTop;

		{
			size_t siz = Bitmap::size(destWidth, destHeight);
			Bitmap *newPtr = (Bitmap *)mem_add(siz + DEFAULT_BLOB2D_INC);
			memset(newPtr, BACKGROUND_COLOR, siz);
			newPtr->init(destWidth, destHeight);

			if( copyWidth > 0 && copyHeight > 0 )
			{
				int yCount = 0;
				unsigned char *src = ptr->get_ptr(copyLeft-left_edge, yCount+copyTop-top_edge );
				unsigned char *dest = newPtr->get_ptr(copyLeft-destLeft, yCount+copyTop-destTop );

				for( ; yCount < copyHeight; ++yCount, src += ptr->get_pitch(), dest += ptr->get_pitch() )
				{
					// unsigned char *src = (yCount+copyTop-top_edge)*width + copyLeft-left_edge;
					// unsigned char *dest = (yCount+copyTop-destTop)*destWdith + copyLeft-destLeft;
					memcpy(dest, src, copyWidth);
				}
			}

			// assign to the newPtr now
			left_edge = destLeft;
			top_edge = destTop;
			width = destWidth;
			height = destHeight;
			if(ptr)
				mem_del(ptr);
			ptr = newPtr;
		}

		// fill rest area with background color
		if( top_edge < copyTop && width > 0)
		{
			fill_area(left_edge, top_edge, left_edge+width-1, copyTop, BACKGROUND_COLOR, 0 );
		}

		// fill bottom
		if( top_edge+height > copyTop+copyHeight && width > 0)
		{
			fill_area(left_edge, copyTop+copyHeight, left_edge+width-1, top_edge+height-1, BACKGROUND_COLOR, 0 );
		}

		// fill left
		if( left_edge < copyLeft && destHeight > 0)
		{
			fill_area(left_edge, copyTop, copyLeft-1, copyTop+copyHeight-1,
				BACKGROUND_COLOR, 0);
		}

		// fill right
		if( left_edge+width > copyLeft+copyWidth && destHeight > 0 )
		{
			fill_area(copyLeft+copyWidth, copyTop, left_edge+width, copyTop+copyHeight-1,
				BACKGROUND_COLOR, 0);
		}
	}

	left_edge = destLeft;
	top_edge = destTop;
	width = destWidth;
	height = destHeight;
}
Пример #27
0
/* Try to interpret a whole incoming packet */
static int baum_eat_packet(BaumDriverState *baum, const uint8_t *buf, int len)
{
    const uint8_t *cur = buf;
    uint8_t req = 0;

    if (!len--)
        return 0;
    if (*cur++ != ESC) {
        while (*cur != ESC) {
            if (!len--)
                return 0;
            cur++;
        }
        DPRINTF("Dropped %d bytes!\n", cur - buf);
    }

#define EAT(c) do {\
    if (!len--) \
        return 0; \
    if ((c = *cur++) == ESC) { \
        if (!len--) \
            return 0; \
        if (*cur++ != ESC) { \
            DPRINTF("Broken packet %#2x, tossing\n", req); \
            if (timer_pending(baum->cellCount_timer)) {    \
                timer_del(baum->cellCount_timer);     \
                baum_cellCount_timer_cb(baum);             \
            } \
            return (cur - 2 - buf); \
        } \
    } \
} while (0)

    EAT(req);
    switch (req) {
    case BAUM_REQ_DisplayData:
    {
        uint8_t cells[baum->x * baum->y], c;
        uint8_t text[baum->x * baum->y];
        uint8_t zero[baum->x * baum->y];
        int cursor = BRLAPI_CURSOR_OFF;
        int i;

        /* Allow 100ms to complete the DisplayData packet */
        timer_mod(baum->cellCount_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +
                       get_ticks_per_sec() / 10);
        for (i = 0; i < baum->x * baum->y ; i++) {
            EAT(c);
            cells[i] = c;
            if ((c & (BRLAPI_DOT7|BRLAPI_DOT8))
                    == (BRLAPI_DOT7|BRLAPI_DOT8)) {
                cursor = i + 1;
                c &= ~(BRLAPI_DOT7|BRLAPI_DOT8);
            }
            if (!(c = nabcc_translation[c]))
                c = '?';
            text[i] = c;
        }
        timer_del(baum->cellCount_timer);

        memset(zero, 0, sizeof(zero));

        brlapi_writeArguments_t wa = {
            .displayNumber = BRLAPI_DISPLAY_DEFAULT,
            .regionBegin = 1,
            .regionSize = baum->x * baum->y,
            .text = (char *)text,
            .textSize = baum->x * baum->y,
            .andMask = zero,
            .orMask = cells,
            .cursor = cursor,
            .charset = (char *)"ISO-8859-1",
        };

        if (brlapi__write(baum->brlapi, &wa) == -1)
            brlapi_perror("baum brlapi_write");
        break;
    }
    case BAUM_REQ_SetMode:
    {
        uint8_t mode, setting;
        DPRINTF("SetMode\n");
        EAT(mode);
        EAT(setting);
        /* ignore */
        break;
    }
    case BAUM_REQ_SetProtocol:
    {
        uint8_t protocol;
        DPRINTF("SetProtocol\n");
        EAT(protocol);
        /* ignore */
        break;
    }
    case BAUM_REQ_GetDeviceIdentity:
    {
        uint8_t identity[17] = { BAUM_RSP_DeviceIdentity,
            'B','a','u','m',' ','V','a','r','i','o' };
        DPRINTF("GetDeviceIdentity\n");
        identity[11] = '0' + baum->x / 10;
        identity[12] = '0' + baum->x % 10;
        baum_write_packet(baum, identity, sizeof(identity));
        break;
    }
    case BAUM_REQ_GetVersionNumber:
    {
        uint8_t version[] = { BAUM_RSP_VersionNumber, 1 }; /* ? */
        DPRINTF("GetVersionNumber\n");
        baum_write_packet(baum, version, sizeof(version));
        break;
    }
    case BAUM_REQ_GetSerialNumber:
    {
        uint8_t serial[] = { BAUM_RSP_SerialNumber,
            '0','0','0','0','0','0','0','0' };
        DPRINTF("GetSerialNumber\n");
        baum_write_packet(baum, serial, sizeof(serial));
        break;
    }
    case BAUM_REQ_GetKeys:
    {
        DPRINTF("Get%0#2x\n", req);
        /* ignore */
        break;
    }
    default:
        DPRINTF("unrecognized request %0#2x\n", req);
        do
            if (!len--)
                return 0;
        while (*cur++ != ESC);
        cur--;
        break;
    }
    return cur - buf;
}

/* The other end is writing some data.  Store it and try to interpret */
static int baum_write(CharDriverState *chr, const uint8_t *buf, int len)
{
    BaumDriverState *baum = chr->opaque;
    int tocopy, cur, eaten, orig_len = len;

    if (!len)
        return 0;
    if (!baum->brlapi)
        return len;

    while (len) {
        /* Complete our buffer as much as possible */
        tocopy = len;
        if (tocopy > BUF_SIZE - baum->in_buf_used)
            tocopy = BUF_SIZE - baum->in_buf_used;

        memcpy(baum->in_buf + baum->in_buf_used, buf, tocopy);
        baum->in_buf_used += tocopy;
        buf += tocopy;
        len -= tocopy;

        /* Interpret it as much as possible */
        cur = 0;
        while (cur < baum->in_buf_used &&
                (eaten = baum_eat_packet(baum, baum->in_buf + cur, baum->in_buf_used - cur)))
            cur += eaten;

        /* Shift the remainder */
        if (cur) {
            memmove(baum->in_buf, baum->in_buf + cur, baum->in_buf_used - cur);
            baum->in_buf_used -= cur;
        }

        /* And continue if any data left */
    }
    return orig_len;
}
Пример #28
0
int
umountfs(char *name, char **typelist)
{
	enum clnt_stat clnt_stat;
	struct hostent *hp;
	struct mtablist *mtab;
	struct sockaddr_in saddr;
	struct timeval pertry, try;
	CLIENT *clp;
	size_t len;
	int so, speclen, do_rpc;
	char *mntonname, *mntfromname;
	char *mntfromnamerev;
	char *nfsdirname, *orignfsdirname;
	char *resolved, realname[MAXPATHLEN];
	char *type, *delimp, *hostp, *origname;

	len = 0;
	mtab = NULL;
	mntfromname = mntonname = delimp = hostp = orignfsdirname = NULL;

	/*
	 * 1. Check if the name exists in the mounttable.
	 */
	(void)checkmntlist(name, &mntfromname, &mntonname, &type);
	/*
	 * 2. Remove trailing slashes if there are any. After that
	 * we look up the name in the mounttable again.
	 */
	if (mntfromname == NULL && mntonname == NULL) {
		speclen = strlen(name);
		for (speclen = strlen(name); 
		    speclen > 1 && name[speclen - 1] == '/';
		    speclen--)
			name[speclen - 1] = '\0';
		(void)checkmntlist(name, &mntfromname, &mntonname, &type);
		resolved = name;
		/* Save off original name in origname */
		if ((origname = strdup(name)) == NULL)
			err(1, "strdup");
		/*
		 * 3. Check if the deprecated nfs-syntax with an '@'
		 * has been used and translate it to the ':' syntax.
		 * Look up the name in the mounttable again.
		 */
		if (mntfromname == NULL && mntonname == NULL) {
			if ((delimp = strrchr(name, '@')) != NULL) {
				hostp = delimp + 1;
				if (*hostp != '\0') {
					/*
					 * Make both '@' and ':'
					 * notations equal 
					 */
					char *host = strdup(hostp);
					len = strlen(hostp);
					if (host == NULL)
						err(1, "strdup");
					memmove(name + len + 1, name,
					    (size_t)(delimp - name));
					name[len] = ':';
					memmove(name, host, len);
					free(host);
				}
				for (speclen = strlen(name); 
				    speclen > 1 && name[speclen - 1] == '/';
				    speclen--)
					name[speclen - 1] = '\0';
				name[len + speclen + 1] = '\0';
				(void)checkmntlist(name, &mntfromname,
				    &mntonname, &type);
				resolved = name;
			}
			/*
			 * 4. Check if a relative mountpoint has been
			 * specified. This should happen as last check,
			 * the order is important. To prevent possible
			 * nfs-hangs, we just call realpath(3) on the
			 * basedir of mountpoint and add the dirname again.
			 * Check the name in mounttable one last time.
			 */
			if (mntfromname == NULL && mntonname == NULL) {
				(void)strcpy(name, origname);
				if ((getrealname(name, realname)) != NULL) {
					(void)checkmntlist(realname,
					    &mntfromname, &mntonname, &type);
					resolved = realname;
				}
				/*
				 * All tests failed, return to main()
				 */
				if (mntfromname == NULL && mntonname == NULL) {
					(void)strcpy(name, origname);
					warnx("%s: not currently mounted",
					    origname);
					free(origname);
					return (1);
				}
			}
		}
		free(origname);
	} else
		resolved = name;

	if (checkvfsname(type, typelist))
		return (1);

	hp = NULL;
	nfsdirname = NULL;
	if (!strcmp(type, "nfs")) {
		if ((nfsdirname = strdup(mntfromname)) == NULL)
			err(1, "strdup");
		orignfsdirname = nfsdirname;
		if ((delimp = strchr(nfsdirname, ':')) != NULL) {
			*delimp = '\0';
			hostp = nfsdirname;
			if ((hp = gethostbyname(hostp)) == NULL) {
				warnx("can't get net id for host");
			}
			nfsdirname = delimp + 1;
		}
	}
	/*
	 * Check if the reverse entrys of the mounttable are really the
	 * same as the normal ones.
	 */
	if ((mntfromnamerev = strdup(getmntname(getmntname(mntfromname,
	    NULL, MNTON, &type, NAME), NULL, MNTFROM, &type, NAME))) == NULL)
		err(1, "strdup");
	/*
	 * Mark the uppermost mount as unmounted.
	 */
	(void)getmntname(mntfromname, mntonname, NOTHING, &type, MARK);
	/*
	 * If several equal mounts are in the mounttable, check the order
	 * and warn the user if necessary.
	 */
	if (strcmp(mntfromnamerev, mntfromname ) != 0 &&
	    strcmp(resolved, mntonname) != 0) {
		warnx("cannot umount %s, %s\n        "
		    "is mounted there, umount it first",
		    mntonname, mntfromnamerev);

		/* call getmntname again to set mntcheck[i] to 0 */
		(void)getmntname(mntfromname, mntonname,
		    NOTHING, &type, UNMARK);
		return (1);
	}
	free(mntfromnamerev);
	/*
	 * Check if we have to start the rpc-call later.
	 * If there are still identical nfs-names mounted,
	 * we skip the rpc-call. Obviously this has to
	 * happen before unmount(2), but it should happen
	 * after the previous namecheck.
	 */
	if (strcmp(type, "nfs") == 0 && getmntname(mntfromname, NULL, NOTHING,
	    &type, COUNT) != NULL)
		do_rpc = 1;
	else
		do_rpc = 0;
	if (!namematch(hp))
		return (1);
	if (unmount(mntonname, fflag) != 0 ) {
		warn("unmount of %s failed", mntonname);
		return (1);
	}
	if (vflag)
		(void)printf("%s: unmount from %s\n", mntfromname, mntonname);
	/*
	 * Report to mountd-server which nfsname
	 * has been unmounted.
	 */
	if (hp != NULL && !(fflag & MNT_FORCE) && do_rpc) {
		memset(&saddr, 0, sizeof(saddr));
		saddr.sin_family = AF_INET;
		saddr.sin_port = 0;
		memmove(&saddr.sin_addr, hp->h_addr, 
		    MIN(hp->h_length, sizeof(saddr.sin_addr)));
		pertry.tv_sec = 3;
		pertry.tv_usec = 0;
		so = RPC_ANYSOCK;
		if ((clp = clntudp_create(&saddr,
		    RPCPROG_MNT, RPCMNT_VER1, pertry, &so)) == NULL) {
			clnt_pcreateerror("Cannot MNT PRC");
			return (1);
		}
		clp->cl_auth = authunix_create_default();
		try.tv_sec = 20;
		try.tv_usec = 0;
		clnt_stat = clnt_call(clp, RPCMNT_UMOUNT, xdr_dir,
		    nfsdirname, xdr_void, (caddr_t)0, try);
		if (clnt_stat != RPC_SUCCESS) {
			clnt_perror(clp, "Bad MNT RPC");
			return (1);
		}
		/*
		 * Remove the unmounted entry from /var/db/mounttab.
		 */
		if (read_mtab(mtab)) {
			mtab = mtabhead;
			clean_mtab(hostp, nfsdirname);
			if(!write_mtab())
				warnx("cannot remove entry %s:%s",
				    hostp, nfsdirname);
			free_mtab();
		}
		free(orignfsdirname);
		auth_destroy(clp->cl_auth);
		clnt_destroy(clp);
	}
Пример #29
0
SEXP shift(SEXP obj, SEXP k, SEXP fill, SEXP type) {

  size_t size;
  int protecti=0;
  SEXP x, tmp=R_NilValue, elem, ans, thisfill, klass;
  unsigned long long *dthisfill;
  enum {LAG, LEAD/*, SHIFT, CYCLIC*/} stype = LAG; // currently SHIFT maps to LAG and CYCLIC is unimplemented (see comments in #1708)
  if (!xlength(obj)) return(obj); // NULL, list()
  if (isVectorAtomic(obj)) {
    x = PROTECT(allocVector(VECSXP, 1)); protecti++;
    SET_VECTOR_ELT(x, 0, obj);
  } else x = obj;
  if (!isNewList(x))
    error("x must be a list, data.frame or data.table");
  if (length(fill) != 1)
    error("fill must be a vector of length 1");
  // the following two errors should be caught by match.arg() at the R level
  if (!isString(type) || length(type) != 1)
    error("Internal error: invalid type for shift(), should have been caught before. please report to data.table issue tracker"); // # nocov
  if (!strcmp(CHAR(STRING_ELT(type, 0)), "lag")) stype = LAG;
  else if (!strcmp(CHAR(STRING_ELT(type, 0)), "lead")) stype = LEAD;
  else if (!strcmp(CHAR(STRING_ELT(type, 0)), "shift")) stype = LAG; // when we get rid of nested if branches we can use SHIFT, for now it maps to LAG
  else error("Internal error: invalid type for shift(), should have been caught before. please report to data.table issue tracker"); // # nocov

  int nx = length(x), nk = length(k);
  if (!isInteger(k)) error("Internal error: k must be integer"); // # nocov
  const int *kd = INTEGER(k);
  for (int i=0; i<nk; i++) if (kd[i]==NA_INTEGER) error("Item %d of n is NA", i+1);  // NA crashed (#3354); n is called k at C level

  ans = PROTECT(allocVector(VECSXP, nk * nx)); protecti++;
  for (int i=0; i<nx; i++) {
    elem  = VECTOR_ELT(x, i);
    size  = SIZEOF(elem);
    R_xlen_t xrows = xlength(elem);
    switch (TYPEOF(elem)) {
    case INTSXP :
      thisfill = PROTECT(coerceVector(fill, INTSXP)); protecti++;
      int ifill = INTEGER(thisfill)[0];
      for (int j=0; j<nk; j++) {
        R_xlen_t thisk = MIN(abs(kd[j]), xrows);
        SET_VECTOR_ELT(ans, i*nk+j, tmp=allocVector(INTSXP, xrows) );
        int *itmp = INTEGER(tmp);
        size_t tailk = xrows-thisk;
        if ((stype == LAG && kd[j] >= 0) || (stype == LEAD && kd[j] < 0)) {
          // LAG when type = 'lag' and n >= 0 _or_ type = 'lead' and n < 0
          if (tailk > 0) memmove(itmp+thisk, INTEGER(elem), tailk*size);
          for (int m=0; m<thisk; m++) itmp[m] = ifill;
        } else {
          // only two possibilities left: type = 'lead', n>=0 _or_ type = 'lag', n<0
          if (tailk > 0) memmove(itmp, INTEGER(elem)+thisk, tailk*size);
          for (int m=xrows-thisk; m<xrows; m++) itmp[m] = ifill;
        }
        copyMostAttrib(elem, tmp);
        if (isFactor(elem)) setAttrib(tmp, R_LevelsSymbol, getAttrib(elem, R_LevelsSymbol));
      }
      break;

    case REALSXP :
      klass = getAttrib(elem, R_ClassSymbol);
      if (isString(klass) && STRING_ELT(klass, 0) == char_integer64) {
        thisfill = PROTECT(allocVector(REALSXP, 1)); protecti++;
        dthisfill = (unsigned long long *)REAL(thisfill);
        if (INTEGER(fill)[0] == NA_INTEGER)
          dthisfill[0] = NA_INT64_LL;
        else dthisfill[0] = (unsigned long long)INTEGER(fill)[0];
      } else {
        thisfill = PROTECT(coerceVector(fill, REALSXP)); protecti++;
      }
      double dfill = REAL(thisfill)[0];
      for (int j=0; j<nk; j++) {
        R_xlen_t thisk = MIN(abs(kd[j]), xrows);
        SET_VECTOR_ELT(ans, i*nk+j, tmp=allocVector(REALSXP, xrows) );
        double *dtmp = REAL(tmp);
        size_t tailk = xrows-thisk;
        if ((stype == LAG && kd[j] >= 0) || (stype == LEAD && kd[j] < 0)) {
          if (tailk > 0) memmove(dtmp+thisk, REAL(elem), tailk*size);
          for (int m=0; m<thisk; m++) dtmp[m] = dfill;
        } else {
          if (tailk > 0) memmove(dtmp, REAL(elem)+thisk, tailk*size);
          for (int m=tailk; m<xrows; m++) dtmp[m] = dfill;
        }
        copyMostAttrib(elem, tmp);
      }
      break;

    case LGLSXP :
      thisfill = PROTECT(coerceVector(fill, LGLSXP)); protecti++;
      int lfill = LOGICAL(thisfill)[0];
      for (int j=0; j<nk; j++) {
        R_xlen_t thisk = MIN(abs(kd[j]), xrows);
        SET_VECTOR_ELT(ans, i*nk+j, tmp=allocVector(LGLSXP, xrows) );
        int *ltmp = LOGICAL(tmp);
        size_t tailk = xrows-thisk;
        if ((stype == LAG && kd[j] >= 0) || (stype == LEAD && kd[j] < 0)) {
          if (tailk > 0) memmove(ltmp+thisk, LOGICAL(elem), tailk*size);
          for (int m=0; m<thisk; m++) ltmp[m] = lfill;
        } else {
          if (tailk > 0) memmove(ltmp, LOGICAL(elem)+thisk, tailk*size);
          for (int m=tailk; m<xrows; m++) ltmp[m] = lfill;
        }
        copyMostAttrib(elem, tmp);
      }
      break;

    case STRSXP :
      thisfill = PROTECT(coerceVector(fill, STRSXP)); protecti++;
      for (int j=0; j<nk; j++) {
        SET_VECTOR_ELT(ans, i*nk+j, tmp=allocVector(STRSXP, xrows) );
        int thisk = abs(kd[j]);
        if ((stype == LAG && kd[j] >= 0) || (stype == LEAD && kd[j] < 0)) {
          for (int m=0; m<xrows; m++) SET_STRING_ELT(tmp, m, (m < thisk) ? STRING_ELT(thisfill, 0) : STRING_ELT(elem, m - thisk));
        } else {
          for (int m=0; m<xrows; m++) SET_STRING_ELT(tmp, m, (xrows-m <= thisk) ? STRING_ELT(thisfill, 0) : STRING_ELT(elem, m + thisk));
        }
        copyMostAttrib(elem, tmp);
      }
      break;

    case VECSXP :
      thisfill = PROTECT(coerceVector(fill, VECSXP)); protecti++;
      for (int j=0; j<nk; j++) {
        SET_VECTOR_ELT(ans, i*nk+j, tmp=allocVector(VECSXP, xrows) );
        int thisk = abs(kd[j]);
        if ((stype == LAG && kd[j] >= 0) || (stype == LEAD && kd[j] < 0)) {
          for (int m=0; m<xrows; m++) SET_VECTOR_ELT(tmp, m, (m < thisk) ? VECTOR_ELT(thisfill, 0) : VECTOR_ELT(elem, m - thisk));
        } else {
          for (int m=0; m<xrows; m++) SET_VECTOR_ELT(tmp, m, (xrows-m <= thisk) ? VECTOR_ELT(thisfill, 0) : VECTOR_ELT(elem, m + thisk));
        }
        copyMostAttrib(elem, tmp);
      }
      break;

    default :
      error("Unsupported type '%s'", type2char(TYPEOF(elem)));
    }
  }

  UNPROTECT(protecti);
  return isVectorAtomic(obj) && length(ans) == 1 ? VECTOR_ELT(ans, 0) : ans;
}
Пример #30
0
static size_t tls1_1_multi_block_encrypt(EVP_AES_HMAC_SHA256 *key,
	unsigned char *out, const unsigned char *inp, size_t inp_len,
	int n4x)	/* n4x is 1 or 2 */
{
	HASH_DESC	hash_d[8], edges[8];
	CIPH_DESC	ciph_d[8];
	unsigned char	storage[sizeof(SHA256_MB_CTX)+32];
	union {	u64	q[16];
		u32	d[32];
		u8	c[128];	} blocks[8];
	SHA256_MB_CTX	*ctx;
	unsigned int	frag, last, packlen, i, x4=4*n4x;
	size_t		ret = 0;
	u8		*IVs;

	ctx = (SHA256_MB_CTX *)(storage+32-((size_t)storage%32));	/* align */

	frag = (unsigned int)inp_len>>(1+n4x);
	last = (unsigned int)inp_len+frag-(frag<<(1+n4x));
	if (last>frag && ((last+13+9)%64)<(x4-1)) {
		frag++;
		last -= x4-1;
	}

	hash_d[0].ptr = inp;
	for (i=1;i<x4;i++)	hash_d[i].ptr = hash_d[i-1].ptr+frag;

	for (i=0;i<x4;i++) {
		unsigned int len = (i==(x4-1)?last:frag);

		ctx->A[i] = key->md.h[0];
		ctx->B[i] = key->md.h[1];
		ctx->C[i] = key->md.h[2];
		ctx->D[i] = key->md.h[3];
		ctx->E[i] = key->md.h[4];
		ctx->F[i] = key->md.h[5];
		ctx->G[i] = key->md.h[6];
		ctx->H[i] = key->md.h[7];

		/* fix seqnum */
#if defined(BSWAP8)
		blocks[i].q[0] = BSWAP8(BSWAP8(*(u64*)key->md.data)+i);
#else
		blocks[i].c[7] += ((u8*)key->md.data)[7]+i;
		if (blocks[i].c[7] < i) {
			int j;

			for (j=6;j>=0;j--) {
				if (blocks[i].c[j]=((u8*)key->md.data)[j]+1) break;
			}
		}
#endif
		blocks[i].c[8] = ((u8*)key->md.data)[8];
		blocks[i].c[9] = ((u8*)key->md.data)[9];
		blocks[i].c[10] = ((u8*)key->md.data)[10];
		/* fix length */
		blocks[i].c[11] = (u8)(len>>8);
		blocks[i].c[12] = (u8)(len);

		memcpy(blocks[i].c+13,hash_d[i].ptr,64-13);
		hash_d[i].ptr += 64-13;
		hash_d[i].blocks = (len-(64-13))/64;

		edges[i].ptr = blocks[i].c;
		edges[i].blocks = 1;
	}

	/* hash 13-byte headers and first 64-13 bytes of inputs */
	sha256_multi_block(ctx,edges,n4x);
	/* hash bulk inputs */
	sha256_multi_block(ctx,hash_d,n4x);

	memset(blocks,0,sizeof(blocks));
	for (i=0;i<x4;i++) {
		unsigned int		len = (i==(x4-1)?last:frag),
					off = hash_d[i].blocks*64;
		const unsigned char    *ptr = hash_d[i].ptr+off;

		off = len-(64-13)-off;	/* remainder actually */
		memcpy(blocks[i].c,ptr,off);
		blocks[i].c[off]=0x80;
		len += 64+13;		/* 64 is HMAC header */
		len *= 8;		/* convert to bits */
		if (off<(64-8)) {
			blocks[i].d[15] = BSWAP4(len);
			edges[i].blocks = 1;			
		} else {
			blocks[i].d[31] = BSWAP4(len);
			edges[i].blocks = 2;
		}
		edges[i].ptr = blocks[i].c;
	}

	/* hash input tails and finalize */
	sha256_multi_block(ctx,edges,n4x);

	memset(blocks,0,sizeof(blocks));
	for (i=0;i<x4;i++) {
		blocks[i].d[0] = BSWAP4(ctx->A[i]);	ctx->A[i] = key->tail.h[0];
		blocks[i].d[1] = BSWAP4(ctx->B[i]);	ctx->B[i] = key->tail.h[1];
		blocks[i].d[2] = BSWAP4(ctx->C[i]);	ctx->C[i] = key->tail.h[2];
		blocks[i].d[3] = BSWAP4(ctx->D[i]);	ctx->D[i] = key->tail.h[3];
		blocks[i].d[4] = BSWAP4(ctx->E[i]);	ctx->E[i] = key->tail.h[4];
		blocks[i].d[5] = BSWAP4(ctx->F[i]);	ctx->F[i] = key->tail.h[5];
		blocks[i].d[6] = BSWAP4(ctx->G[i]);	ctx->G[i] = key->tail.h[6];
		blocks[i].d[7] = BSWAP4(ctx->H[i]);	ctx->H[i] = key->tail.h[7];
		blocks[i].c[32] = 0x80;
		blocks[i].d[15] = BSWAP4((64+32)*8);
		edges[i].ptr = blocks[i].c;
		edges[i].blocks = 1;
	}

	/* finalize MACs */
	sha256_multi_block(ctx,edges,n4x);

	packlen = 5+16+((frag+32+16)&-16);

	out += (packlen<<(1+n4x))-packlen;
	inp += (frag<<(1+n4x))-frag;

	RAND_bytes((IVs=blocks[0].c),16*x4);	/* ask for IVs in bulk */

	for (i=x4-1;;i--) {
		unsigned int len = (i==(x4-1)?last:frag), pad, j;
		unsigned char *out0 = out;

		out += 5+16;		/* place for header and explicit IV */
		ciph_d[i].inp = out;
		ciph_d[i].out = out;

		memmove(out,inp,len);
		out += len;

		/* write MAC */
		((u32 *)out)[0] = BSWAP4(ctx->A[i]);
		((u32 *)out)[1] = BSWAP4(ctx->B[i]);
		((u32 *)out)[2] = BSWAP4(ctx->C[i]);
		((u32 *)out)[3] = BSWAP4(ctx->D[i]);
		((u32 *)out)[4] = BSWAP4(ctx->E[i]);
		((u32 *)out)[5] = BSWAP4(ctx->F[i]);
		((u32 *)out)[6] = BSWAP4(ctx->G[i]);
		((u32 *)out)[7] = BSWAP4(ctx->H[i]);
		out += 32;
		len += 32;

		/* pad */
		pad = 15-len%16;
		for (j=0;j<=pad;j++) *(out++) = pad;
		len += pad+1;

		ciph_d[i].blocks = len/16;
		len += 16;	/* account for explicit iv */

		/* arrange header */
		out0[0] = ((u8*)key->md.data)[8];
		out0[1] = ((u8*)key->md.data)[9];
		out0[2] = ((u8*)key->md.data)[10];
		out0[3] = (u8)(len>>8);
		out0[4] = (u8)(len);

		/* explicit iv */
		memcpy(ciph_d[i].iv, IVs, 16);
		memcpy(&out0[5],     IVs, 16);

		ret += len+5;

		if (i==0) break;

		out = out0-packlen;
		inp -= frag;
		IVs += 16;
	}

	aesni_multi_cbc_encrypt(ciph_d,&key->ks,n4x);

	OPENSSL_cleanse(blocks,sizeof(blocks));
	OPENSSL_cleanse(ctx,sizeof(*ctx));

	return ret;
}