Пример #1
0
MyClip  *
getBPTags( const char *username, int *total, int *numOfClips )
{
    char    *response;
    char    url[MAX_URLLENGTH];
    char    *p, *q, *r, *s, *t, *u;
    int     num = 0, cnt = 0;
    int     maxNum = 20;    /* 暫定値 */
    int     maxCnt = 0;
    int     yyyy, mm, dd;
    MyClip  *mp = NULL;
    size_t  sz  = MAX_CONTENT_SIZE * 64;

    *total      = 0;
    *numOfClips = 0;
    response = (char *)malloc( sz );
    if ( !response )
        return ( mp );

    sprintf( url, "http://tags.blogpeople.net/user/%s", username );
    setTargetURL( url );
    setUpReceiveBuffer( response, sz );
    p = http_get( url, response );
    if ( !p || !(*p) || !(*response) ) {
        free( response );
        return ( mp );
    }

    p = response;
    if ( p && *p ) {
        q = strstr( p, ">全ブックマーク</a>(" );
        if ( q )
            *total = cnt = atol( q + 20 );
        else {
            q = strstr( p, "件中 1〜20件を表示" );
            if ( q ) {
                do {
                    while ( (*(q - 1) >= '0') && (*(q - 1) <= '9') )
                        q--;
                    cnt += (int)(atol( q ) * pow( 1000.0, (double)num ));
                    num++;
                } while ( *--q == ',' );

                *total = cnt;
            }
            else {
                free( response );
                return ( mp );
            }
        }

        maxNum = ((cnt / 20) + 1) * 20;
        maxCnt = cnt / 20;
        cnt = 0;
        num = 0;
    }

    mp = (MyClip *)malloc( sizeof ( MyClip ) * maxNum );
    if ( mp ) {
        char    tags[80];

        memset( mp, 0x00, sizeof ( MyClip ) * maxNum );
        p = response;

        while ( *p ) {
            u = NULL;
            if ( !strncmp( p, "<div class=\"bookmark-title\">", 28 ) ) {
                q = p + 28;
                u = strstr( q, "</li>" );
                r = strstr( q, "<a href=\"" );
                if ( r ) {
                    r += 9;
                    s = strchr( r, '"' );
                    if ( s ) {
                        strncpy( mp[num].url, r, s - r );
                        mp[num].url[s - r] = NUL;

                        q = strstr( r, "\">" );
                        if ( q ) {
                            q += 2;
                            r = strstr( q, "</a>" );
                            if ( r ) {
                                strncpy( mp[num].title, q, r - q );
                                mp[num].title[r - q] = NUL;
                                p = r + 4;
                            }
                            else
                                p = q;
                        }
                        else
                            p = s + 1;
                    }
                    else
                        p = r;
                }
                else
                    p = q;

                continue;
            }

            if ( !strncmp( p, "<div class=\"bookmark-description\">", 34 ) ) {
                q = p + 34;
                while ( (*q == ' ')  || (*q == '\t') ||
                        (*q == '\r') || (*q == '\n')    )
                    q++;
                r = strstr( q, "<br />" );
                if ( r ) {
                    strncpy( mp[num].comment, q, r - q );
                    mp[num].comment[r - q] = NUL;

                    s = mp[num].comment;
                    while ( ((t = strchr( s, '\n' )) != NULL) ||
                            ((t = strchr( s, '\r' )) != NULL)    ) {
                        if ( (*(t + 1) == '\r') || (*(t + 1) == '\n') )
                            strcpy( t, t + 1 );
                        *t = ' ';
                    }

                    p = r + 6;
                }
                else
                    p = q;

                continue;
            }

            if ( !strncmp( p, "<div class=\"sublink\">", 21 ) ) {
                p = q = p + 21;
                r = strstr( q, "Tag: " );
                if ( r ) {
                    mp[num].tags[0] = NUL;
                    r += 5;
                    p = r;
                    do {
                        tags[0] = NUL;
                        s = strstr( r, "<a href=\"" );
                        t = strchr( r, ' ' );
                        if ( s && ((s < t) || (s == t + 1)) ) {
                            r = s + 9;
                            s = strchr( r, '>' );
                            if ( s ) {
                                s++;
                                t = strstr( s, "</a>" );
                                if ( t ) {
                                    strncpy( tags, s, t - s );
                                    tags[t - s] = NUL;
                                    p = r = t + 4;

                                    if ( mp[num].tags[0] != NUL )
                                        strcat( mp[num].tags, " " );
                                    strcat( mp[num].tags, tags );
                                }
                                else
                                    break;
                            }
                            else
                                break;
                        }
                        else
                            break;
                    } while ( r );

                    if ( !strncmp( p, "  <a href=\"/url/", 16 ) ) {
                        /* 「他:n人がリンク」 をスキップ */
                        p += 16;
                        q = strstr( p, "</a>" );
                        if ( q )
                            p = q + 4;
                    }
                    while ( p && ((*p < '0') || (*p > '9')) )
                        p++;
                    if ( p ) {
                        q = p;
                        yyyy = 2000 + (*q - '0') * 10 + (*(q + 1) - '0');
                        q += 2;

                        while ( *q && ((*q < '0') || (*q > '9')) )
                            q++;
                        mm   = (*q - '0') * 10 + (*(q + 1) - '0');
                        q += 2;

                        while ( *q && ((*q < '0') || (*q > '9')) )
                            q++;
                        dd   = (*q - '0') * 10 + (*(q + 1) - '0');
                        q += 2;

                        mp[num].yyyy = yyyy;
                        mp[num].mm   = mm;
                        mp[num].dd   = dd;
                        mp[num].HH   = 0;
                        mp[num].MM   = 0;
                        mp[num].SS   = 0;

                        p = q;

                        // 評価(マイレート)
                        if (((q = strstr(p, "alt=\"マイレート: ")) != NULL) &&
                            (q < u) ) {
                            long    rate;

                            q += 17;
                            rate = atol( q );
                            p = q + 1;

                            if ( rate > 0 ) {
#ifdef  OLD_FASHIONED
                                //   -- MM/Memo 互換の方法で記録する
                                //        title の前に (評価) を付加する
                                char    tmpTitle[BUFSIZ * 2];

                                sprintf( tmpTitle, "(%d)『%s』",
                                         rate, mp[num].title );
                                strcpy( mp[num].title, tmpTitle );
#else
                                // 「評価」は mp[num].evaluation に格納する
                                mp[num].evaluation = rate;
#endif
                            }
                        }

                        num++;
                        if ( num >= maxNum )
                            break;
                        mp[num].tags[0] = NUL;

                        if ( (num % 20) == 0 ) {
                            /* 次のページを読む */
                            cnt++;
                            if ( cnt > maxCnt )
                                break;
                            memset( response, 0x00, MAX_CONTENT_SIZE * 20 );
                            sprintf( url,
                                     "http://tags.blogpeople.net/user/%s/%d",
                                     username, cnt );
                            setTargetURL( url );
                            setUpReceiveBuffer( response, sz );
                            p = http_get( url, response );
                            if ( !p || !(*p) || !(*response) )
                                break;
                            p = response;
                            continue;
                        }
                    }
                }

                continue;
            }

            p++;
        }
    }

    *numOfClips = num;
    free( response );

    return ( mp );
}
Пример #2
0
long
getNumberOfBookmarksOnDelicious(
        const char *userName,   /* (I) ユーザ名   */
        const char *password    /* (I) パスワード */
    )
{
    long    num = 0;
    long    n;
    char    url[BUFSIZ];
    char    cookie[MAX_COOKIE_LEN];
    char    *response;
    size_t  sz;
    int     r;

    cookie[0] = NUL;
    if ( !userName )
        userName = xmlrpc_p->userName;
    if ( !password )
        password = xmlrpc_p->password;

    sz = MAX_CONTENT_SIZE * 16;
    response = (char *)malloc( sz );
    if ( !response )
        return ( num );

    sprintf( url, "http://delicious.com/%s/", userName );
    setUpReceiveBuffer( response, sz );

    r = loginDelicious( userName, password, cookie );
    if ( r )
        http_getEx( url, response, cookie );
    else
        http_get( url, response );
    if ( response[0] ) {
        char    *p = strstr( response, "<span id=\"tagScopeCount\">" );
        if ( p ) {
            char    *q;
            
            p = strchr( p, '>' ) + 1;
            q = strstr( p, "</" );
            if ( q ) {
                num = atol( p );
                free( response );
                return ( num );
            }
        }
    }

#ifdef  BEFORE_20060809
    strcpy( url, "http://del.icio.us/api/posts/dates" );
#else
    strcpy( url, "https://api.del.icio.us/v1/posts/dates" );
#endif

    setUpReceiveBuffer( response, sz );
    http_getBASIC( url, userName, password, response );
    if ( response && *response ) {
        char    *p = strstr( response, "<dates tag=\"" );

        if ( p ) {
            char    *q, *r;

            p += 12;
            while ( ( q = strstr( p, "<date " ) ) != NULL ) {
                q += 6;

                /* count */
                r = strstr( q, "count=\"" );
                if ( r ) {
                    r += 7;
                    n = atol( r );
                    num += n;
                }

                p = strchr( q, '>' );
                if ( !p )
                    break;
            }
        }
    }
    free( response );

    return ( num );
}
Пример #3
0
/**
 * Get a URL from the cache, add it if it does not exist
 * @param cache The cache
 * @param session the (optional) session requesting the URL
 * @param url The URL
 * @param download If true, the file will be downloaded if it does not exist in the cache.
 * @param pool The pool to use for allocating the filename
 * @return The filename or NULL if there is an error
 */
static char *url_cache_get(url_cache_t *cache, switch_core_session_t *session, const char *url, int download, switch_memory_pool_t *pool)
{
	char *filename = NULL;
	cached_url_t *u = NULL;
	if (zstr(url)) {
		return NULL;
	}

	url_cache_lock(cache, session);
	u = switch_core_hash_find(cache->map, url);

	if (u && u->status == CACHED_URL_AVAILABLE) {
		if (switch_time_now() >= (u->download_time + u->max_age)) {
			switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Cached URL has expired.\n");
			url_cache_remove_soft(cache, session, u); /* will get permanently deleted upon replacement */
			u = NULL;
		} else if (switch_file_exists(u->filename, pool) != SWITCH_STATUS_SUCCESS) {
			switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Cached URL file is missing.\n");
			url_cache_remove_soft(cache, session, u); /* will get permanently deleted upon replacement */
			u = NULL;
		}
	}

	if (!u && download) {
		/* URL is not cached, let's add it.*/
		/* Set up URL entry and add to map to prevent simultaneous downloads */
		cache->misses++;
		switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Cache MISS: size = %zu (%zu MB), hit ratio = %d/%d\n", cache->queue.size, cache->size / 1000000, cache->hits, cache->hits + cache->misses);
		u = cached_url_create(cache, url);
		if (url_cache_add(cache, session, u) != SWITCH_STATUS_SUCCESS) {
			/* This error should never happen */
			url_cache_unlock(cache, session);
			switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_CRIT, "Failed to add URL to cache!\n");
			cached_url_destroy(u, cache->pool);
			return NULL;
		}

		/* download the file */
		url_cache_unlock(cache, session);
		if (http_get(cache, u, session) == SWITCH_STATUS_SUCCESS) {
			/* Got the file, let the waiters know it is available */
			url_cache_lock(cache, session);
			u->status = CACHED_URL_AVAILABLE;
			filename = switch_core_strdup(pool, u->filename);
			cache->size += u->size;
		} else {
			/* Did not get the file, flag for replacement */
			url_cache_lock(cache, session);
			url_cache_remove_soft(cache, session, u);
			switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Failed to download URL %s\n", url);
			cache->errors++;
		}
	} else if (!u) {
		filename = DOWNLOAD_NEEDED;
	} else {
		/* Wait until file is downloaded */
		if (u->status == CACHED_URL_RX_IN_PROGRESS) {
			switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "Waiting for URL %s to be available\n", url);
			u->waiters++;
			url_cache_unlock(cache, session);
			while(u->status == CACHED_URL_RX_IN_PROGRESS) {
				switch_sleep(10 * 1000); /* 10 ms */
			}
			url_cache_lock(cache, session);
			u->waiters--;
		}

		/* grab filename if everything is OK */
		if (u->status == CACHED_URL_AVAILABLE) {
			filename = switch_core_strdup(pool, u->filename);
			cache->hits++;
			u->used = 1;
			switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "Cache HIT: size = %zu (%zu MB), hit ratio = %d/%d\n", cache->queue.size, cache->size / 1000000, cache->hits, cache->hits + cache->misses);
		}
	}
	url_cache_unlock(cache, session);
	return filename;
}
Пример #4
0
/**
 * Simple command-line HTTP client.
 */
int main( int argc, char *argv[ ] )
{
  int client_connection;
  char *host, *path;
  char *proxy_host, *proxy_user, *proxy_password;
  int proxy_port;
  struct hostent *host_name;
  struct sockaddr_in host_address;
  int ind;
#ifdef WIN32
  WSADATA wsaData;
#endif

  if ( argc < 2 )
  {
    fprintf( stderr, 
      "Usage: %s: [-p http://[username:password@]proxy-host:proxy-port] <URL>\n", 
      argv[ 0 ] );
    return 1;
  }

  proxy_host = proxy_user = proxy_password = host = path = NULL;
  ind = 1;
  if ( !strcmp( "-p", argv[ ind ] ) )
  {
    if ( !parse_proxy_param( argv[ ++ind ], &proxy_host, &proxy_port,
                             &proxy_user, &proxy_password ) )
    {
      fprintf( stderr, "Error - malformed proxy parameter '%s'.\n", argv[ 2 ] );
      return 2;
    }
    ind++;
  }

  if ( parse_url( argv[ ind ], &host, &path ) == -1 )
  {
    fprintf( stderr, "Error - malformed URL '%s'.\n", argv[ 1 ] );
    return 1;
  }

  printf( "Connecting to host '%s'\n", host );
  // Step 1: open a socket connection on http port with the destination host.
#ifdef WIN32
  if ( WSAStartup( MAKEWORD( 2, 2 ), &wsaData ) != NO_ERROR )
  {
    fprintf( stderr, "Error, unable to initialize winsock.\n" );
    return 2;
  }
#endif

  client_connection = socket( PF_INET, SOCK_STREAM, 0 );

  if ( !client_connection )
  {
    perror( "Unable to create local socket" );
    return 2;
  }

  if ( proxy_host )
  {
    printf( "Connecting to host '%s'\n", proxy_host );
    host_name = gethostbyname( proxy_host );
  } 
  else
  {
    host_name = gethostbyname( host );
  }

  if ( !host_name )
  {
    perror( "Error in name resolution" );
    return 3;
  }

  host_address.sin_family = AF_INET;
  host_address.sin_port = htons( proxy_host ? proxy_port : HTTP_PORT  );
  memcpy( &host_address.sin_addr, host_name->h_addr_list[ 0 ], 
          sizeof( struct in_addr ) );

  if ( connect( client_connection, ( struct sockaddr * ) &host_address, 
       sizeof( host_address ) ) == -1 )
  {
    perror( "Unable to connect to host" );
    return 4;
  }

  printf( "Retrieving document: '%s'\n", path );
  http_get( client_connection, path, host, proxy_host,
            proxy_user, proxy_password );

  display_result( client_connection );

  printf( "Shutting down.\n" );

#ifdef WIN32
  if ( closesocket( client_connection ) == -1 )
#else
  if ( close( client_connection ) == -1 )
#endif
  {
    perror( "Error closing client connection" );
    return 5;
  }

#ifdef WIN32
  WSACleanup();
#endif

  return 0;
}
Пример #5
0
/* Yahoo! Japan に login する */
int
loginYahooJapan(
        const char *username,   // (I)   ユーザ名 (Yahoo! Japan ID)
        const char *password,   // (I)   パスワード
        char       *cookie      // (I/O) クッキー
    )
{
    int     ret   = 0;
    int     retry = 5;
    char    *request;
    char    *response;
    char    url[MAX_URLLENGTH];
    char    challenge[MAX_KEYLENGTH];
    size_t  sz = MAX_CONTENT_SIZE * 4;

    if ( !cookie   ||
         !username || !(*username) ||
         !password || !(*password)    )
         return ( ret );

    request  = (char *)malloc( MAX_CONTENT_SIZE );
    if ( !request ) 
        return ( ret );
    response = (char *)malloc( sz );
    if ( !response ) {
        free( request );
        return ( ret );
    }

    // http://bookmarks.yahoo.co.jp/all を GET
    challenge[0] = NUL;
    setUpReceiveBuffer( response, sz );
    http_get( "http://bookmarks.yahoo.co.jp/all", response );
    if ( *response ) {
        char    *p, *q;

        p = strstr( response, "name=\".challenge\" value=\"" );
        if ( p ) {
            p += 25;
            q = strchr( p, '"' );
            if ( q ) {
                strncpy( challenge, p, q - p );
                challenge[q - p] = NUL;
            }
        }
    }

    if ( challenge[0] ) {
        do {
            memset( request,  0x00, MAX_CONTENT_SIZE );

            strcpy( url, "https://login.yahoo.co.jp/config/login" );
            setTargetURL( url );
            sprintf( request,
                     ".done=%s&"
                     ".src=bmk2&"
                     ".challenge=%s&"
                     ".chkP=Y&"
                     "login=%s&"
                     "passwd=%s&"
                     ".persistent=Y&",
                     encodeURL( "http://bookmarks.yahoo.co.jp/all" ),
                     challenge,
                     username, password );
            sprintf( request + strlen( request ),
                     "submit=%s",
                     encodeURL(sjis2utf("ログイン")) );
            setUpReceiveBuffer( response, sz );
            http_postEx( url, "application/x-www-form-urlencoded",
                         request, response, cookie );

            if ( *response ) {
                char    *p, *q;

                p = strstr( response,
                            "<meta http-equiv=\"Refresh\" content=\"0; url=" );
                if ( p ) {
                    p += 43;
                    q = strchr( p, '"' );
                    if ( q ) {
                        strncpy( url, p, q - p );
                        url[q - p] = NUL;
                        setUpReceiveBuffer( response, sz );
                        http_getEx( url, response, cookie );
                    }
                }

                if ( *response ) {
                    if ( strstr( response,
                     "http://login.yahoo.co.jp/config/login?logout") != NULL )
                        ret = 1;    /* ログイン成功 */
                    else
                        ret = 0;    /* ログイン失敗 */
                }
            }
            else
                ret = 0;        /* ログイン失敗 */

            if ( ret == 0 ) {
                retry--;
                if ( retry <= 0 )
                    break;
                Sleep( 2000 );
            }
        } while ( ret == 0 );
    }

    free( response );
    free( request  );

    return ( ret );
}
Пример #6
0
int ztest_search (void *handle, bend_search_rr *rr)
{
  int err;
  char query[1024];
  char query_final[2048];
  char err_string[255];
  int i;
  
  if (strcmp(rr->setname,"1")) {
    rr->errcode = 2;
    return 0;
  }
    
   //Si la requete n'est pas de type_1
  if (rr->query->which!=2) {
    rr->errcode = 107;
    return 0;
  }

  err=get_query(query,rr->query->u.type_1->RPNStructure,err_string,0);
  if (!err) {  
    yaz_log(LOG_LOG,"Translated Query = %s",query);
  } else {
      rr->errcode = err;
      rr->errstring = err_string;
      return 0;
    }

    if (rr->num_bases != 1)
    {
        rr->errcode = 23;
        return 0;
    }
    if (yaz_matchstr (rr->basenames[0], database))
    {
        rr->errcode = 109;
        rr->errstring = rr->basenames[0];
        return 0;
    }
  
  	/* Lancement de la recherche */
  	sprintf(query_final,"query=%s&command=search",url_encode(query));
  	yaz_log(LOG_LOG,"query:%s",query_final);
  	
  	if (http_get(query_final)) {
  		rr->errcode=2;
  		return 0;	
  	}
  	if (http_err==3) {
  			rr->errcode=114;
  			rr->errstring=http_err_string;
  			return 0;
  	}
  	strcpy(id_set,http_content);
  	
  	n_results=atoi(strtok(id_set,"@"));
  	cur_results=0;
  	i=0;
  	while ((ids[i]=strtok(NULL,"@"))!=NULL) {
  		i++;
  	}
 	
 	rr->hits = n_results;
    return 0;
}
Пример #7
0
int
_getYJbookmark(
        const char *userName,
        char       *cookie,
        MyClip     **mp,
        MyClipEx   **mpEx,
        char       *response,
        size_t     sz,
        int        *total
    )
{
    char    target[MAX_URLLENGTH];
    char    url[MAX_URLLENGTH];
    BOOL    cont = TRUE;
    char    *p, *q, *r, *s;
    int     num  = 0;
    int     cnt  = 0;
    int     unit = 200;
    int     page = 1;
    int     yy, mm, dd;
    char    tmp[MAX_DESCRIPTION_LEN * 2];

    sprintf( target, "http://bookmarks.yahoo.co.jp/%s",
             cookie ? "my" : userName );
    strcpy( url, target );
    do {
        setUpReceiveBuffer( response, sz );
        setTargetURL( url );
        if ( cookie )
            http_getEx( url, response, cookie );
        else
            http_get( url, response );

        if ( !(*response) )
            break;

        if ( *total == 0 ) {
            // 全部で何件あるか、前もって調べておく
            p = strstr( response, sjis2utf("</strong>件 ]</h6>") );
            if ( p ) {
                while ( *--p && ((*p >= '0') && (*p <= '9')) )
                    if ( p <= response )
                        break;
                if ( *++p ) {
                    if ( *p == '0' )
                        p++;
                    *total = atol( p );
                }
            }
        }

        // ブックマークを抜き出す
        p = strstr( response, "<div id=\"visiblebms\">" );
        if ( !p )
            break;
        p += 21;

        do {
            if ( mp ) {
                MyClip  *np;
                np = allocateMyClipIfNecessary( mp, unit, &cnt, num );
                if ( !np )
                    break;
                *mp = np;
            }
            if ( mpEx ) {
                MyClipEx    *np;
                np = allocateMyClipExIfNecessary( mpEx, unit, &cnt, num );
                if ( !np )
                    break;
                *mpEx = np;
            }

            q = strstr( p, "<div class=\"saveitem\"" );
            s = strstr( p, "<div class=\"clr\"></div>" );
            if ( !s )
                s = strstr( p, "<div class=\"selectarea\">" );
            if ( !q || !s )
                break;
            p = q + 21;

            // ID
            q = strstr( p, " id=\"" );
            if ( !q || (q > s) )
                break;
            p = q + 5;
            q = strstr( p, "\">" );
            if ( !q || (q > s) )
                break;
            if ( !strncmp( p, "fakenode", 8 ) )
                break;
            if ( mpEx ) {
                strncpy( (*mpEx)[num].entryID, p, q - p );
                (*mpEx)[num].entryID[q - p] = NUL;
            }
            p = q + 2;

            // URL
            q = strstr( p, "<h4 class=\"title\"><a href=\"" );
            if ( !q || (q > s) )
                break;
            p = q + 27;
            if ( !strncmp( p, "http://srd.yahoo.co.jp/BMK/", 27 ) ) {
                q = strstr( p, "/**" );
                if ( !q || (q > s) )
                    break;
                p = q + 3;
            }
            q = strstr( p, "\" " );
            if ( !q || (q > s) )
                break;
            strncpy( tmp, p, q - p );
            tmp[q - p] = NUL;
            while ( ( r = strstr( tmp, "%3A" ) ) != NULL ) {
                *r = ':';
                strcpy( r + 1, r + 3 );
            }
            if ( mp )
                strcpy( (*mp)[num].url, tmp );
            if ( mpEx )
                strcpy( (*mpEx)[num].url, tmp );
            p = q + 2;

            // タイトル
            q = strstr( p, "\">" );
            if ( !q || (q > s) )
                break;
            p = q + 2;
            q = strstr( p, "</a>" );
            if ( !q || (q > s) )
                break;
            strncpy( tmp, p, q - p );
            tmp[q - p] = NUL;
            r = utf2sjis( tmp );
            if ( !r )
                utf2sjisEx( tmp );
            else
                strcpy( tmp, r );
            if ( mp )
                strcpy( (*mp)[num].title, tmp );
            if ( mpEx )
                strcpy( (*mpEx)[num].title, tmp );
            p = q + 4;

            // コメント
            q = strstr( p, "<div class=\"desc\">" );
            if ( q && (q < s) ) {
                // コメントが存在する場合
                p = q + 18;

                r = strstr( p, sjis2utf("コメント:</span>") );
                if ( r && (r < s) ) {
                    p = strstr( r, ":</span>" ) + 8;
                    while ( (*p == ' ') || (*p == '\t') )
                        p++;
                }

                q = strstr( p, "</div>" );
                if ( !q || (q > s) )
                    break;
                strncpy( tmp, p, q - p );
                tmp[q - p] = NUL;
                r = utf2sjis( tmp );
                if ( !r )
                    utf2sjisEx( tmp );
                else
                    strcpy( tmp, r );
                if ( mp )
                    strcpy( (*mp)[num].comment, tmp );
                if ( mpEx )
                    strcpy( (*mpEx)[num].comment, tmp );
                p = q + 6;
            }

            // タグ
            q = strstr( p, "<div class=\"tags\">" );
            if ( q && (q < s) ) {
                // タグが存在する場合
                int len;

                p = q + 18;

                tmp[0] = NUL;
                p = strchr( q, '>' ) + 1;
                do {
                    q = strstr( p, "<li><a " );
                    if ( !q || (q > s) )
                        break;
                    q += 7;
                    p = strchr( q, '>' );
                    if ( !p )
                        break;
                    p++;
                    q = strstr( p, "</a>" );
                    if ( !q )
                        break;

                    if ( tmp[0] == NUL )
                        len = 0;
                    else {
                        strcat( tmp, " " );
                        len = strlen( tmp );
                    }
                    strncat( tmp, p, q - p );
                    tmp[len + (q - p)] = NUL;

                    p = q + 4;
                } while ( p < s );
                if ( tmp[0] ) {
                    r = utf2sjis( tmp );
                    if ( !r )
                        utf2sjisEx( tmp );
                    else
                        strcpy( tmp, r );
                }
                if ( mp )
                    strcpy( (*mp)[num].tags, tmp );
                if ( mpEx )
                    strcpy( (*mpEx)[num].tags, tmp );
            }

            // 年月日 (時分秒は取得できない)
            q = strstr( p, "<span class=\"savedate\">" );
            if ( !q || (q > s) )
                break;
            p = q + 23;
            while ( *p && ((*p < '0') || (*p > '9')) && (p < s) )
                p++;
            if ( !(*p) || (p > s) )
                break;
            yy = atol( p );

            while ( (*p >= '0') && (*p <= '9') )
                p++;
            while ( (*p < '0') || (*p > '9') )
                p++;
            mm = atol( p );

            while ( (*p >= '0') && (*p <= '9') )
                p++;
            while ( (*p < '0') || (*p > '9') )
                p++;
            dd = atol( p );

            if ( mp ) {
                (*mp)[num].yyyy = yy;
                (*mp)[num].mm   = mm;
                (*mp)[num].dd   = dd;
                (*mp)[num].HH   = 0;
                (*mp)[num].MM   = 0;
                (*mp)[num].SS   = 0;
            }

            // 公開・非公開
            q = strstr( p, "<em class=\"me\">" );
            if ( q && (q < s) )
                if ( mp )
                    (*mp)[num].publication = PUB_PRIVATE;

            p = strchr( s, '>' );
            num++;
            if ( (*total > 0) && (num >= *total) ) {
                cont = FALSE;
                break;
            }
        } while ( p && *p );

        if ( cont ) {
            // 次へ
            cont = FALSE;
            if ( strstr( response, sjis2utf("class=\"next\">次へ") ) ) {
                page++;
                sprintf( url,
                         "%s?orderby=ctime&b=%d&sort=DESC",
                         target, page );
                cont = TRUE;
                Sleep( 1000 );
            }
        }
    } while ( cont );

    return ( num );
}
Пример #8
0
int start_server(const char *url, const char *rtspport)
{
  int mediafd = -1, listenfd, tempfd, maxfd;
  int videofd;
  struct addrinfo *info;
  struct sockaddr_storage remoteaddr;
  socklen_t addrlen = sizeof remoteaddr;
  fd_set readfds, masterfds;
  int nready, i;
  int videosize, videoleft;
  int recvd, sent;
  char urlhost[URLSIZE], urlpath[URLSIZE], tempstr[URLSIZE];
  unsigned char msgbuf[BUFSIZE], sendbuf[BUFSIZE];
  char *temp;
  RTSPMsg rtspmsg;
  Client streamclient;


  /* The current state of the protocol */
  int mediastate = IDLE;
  int quit = 0;

  init_client(&streamclient);

  /* Open the a file where the video is to be stored */
  if ((videofd = open("videotemp.mp4", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) < 0) {
    fatal_error("Error opening the temporary videofile");
  }

  /* Create the RTSP listening socket */
  resolve_host(NULL, rtspport, SOCK_STREAM, AI_PASSIVE, &info);
  listenfd = server_socket(info);
  maxfd = listenfd;


  FD_ZERO(&readfds);
  FD_ZERO(&masterfds);
  FD_SET(listenfd, &masterfds);


  while (!quit) {

    readfds = masterfds;

    if ((nready = Select(maxfd + 1, &readfds, NULL)) == -1) {
      write_log(logfd, "Select interrupted by a signal\n");
    } 

    for (i = 0; i <= maxfd; i++) {
      if (FD_ISSET(i, &readfds)) {

        nready--;

        /* New connection from a client */
        if (i == listenfd) {
          if ((tempfd = accept(i, (struct sockaddr *)&remoteaddr, &addrlen)) == -1) {
            if (errno != EWOULDBLOCK && errno != ECONNABORTED &&
                errno != EPROTO && errno != EINTR)
            {
              fatal_error("accept");
            }
          }

          /* If we are already serving a client, close the new connection. Otherwise, continue. */
          if (streamclient.state != NOCLIENT) close (tempfd);
          else {
            streamclient.rtspfd = tempfd;
            streamclient.state = CLICONNECTED;
            maxfd = max(2, streamclient.rtspfd, maxfd);
            FD_SET(streamclient.rtspfd, &masterfds);
          }
        }

        /* Data from the media source */
        else if (i == mediafd) {

          switch (mediastate) {

            case GETSENT:
              /* Read ONLY the HTTP message from the socket and store the video size */
              recvd = recv_all(i, msgbuf, BUFSIZE, MSG_PEEK);
              temp = strstr((char *)msgbuf, "\r\n\r\n");
              recvd = recv_all(i, msgbuf, (int)(temp + 4 - (char *)msgbuf), 0);
              temp = strstr((char *)msgbuf, "Content-Length:");
              sscanf(temp, "Content-Length: %d", &videosize);
              videoleft = videosize;
              mediastate = RECVTCP;
              break;

            case RECVTCP:
              if ((recvd = recv_all(i, msgbuf, BUFSIZE, 0)) == 0) {
                FD_CLR(i, &masterfds);
                close(i);
                printf("Socket closed\n");
              }
              writestr(videofd, msgbuf, recvd);
              videoleft -= recvd;
              if (videoleft <= 0) mediastate = STREAM;
              break;

              /* TODO: Start streaming, currently just exits the program */
            case STREAM:
              /*
                 close(videofd);
                 close(mediafd);
                 close(listenfd);
                 quit = 1;
                 */
              break;

            default: 
              break;
          }
        }

        /* Data from a client ( i == streamclient.rtspfd) */
        else {

          if ((recvd = recv_all(i, msgbuf, BUFSIZE, 0)) == 0) {
            FD_CLR(i, &masterfds);
            close(i);
            printf("Socket closed\n");
            streamclient.state = NOCLIENT;
          }
          else {
            printf("%s", msgbuf);
            parse_rtsp(&rtspmsg, msgbuf); 
          }

          switch (streamclient.state) {

            case CLICONNECTED:
              if (rtspmsg.type == OPTIONS) {
                sent = rtsp_options(&rtspmsg, sendbuf);
                send_all(i, sendbuf, sent);
              }
              else if (rtspmsg.type == DESCRIBE) {

                /* Start fetching the file from the server */
                parse_url(url, urlhost, urlpath);
                resolve_host(urlhost, "80", SOCK_STREAM, 0, &info);
                mediafd = client_socket(info, 0);
                FD_SET(mediafd, &masterfds);
                maxfd = max(2, maxfd, mediafd);

                /* Send the GET message */
                http_get(url, msgbuf);
                send_all(mediafd, msgbuf, strlen((char *)msgbuf));
                mediastate = GETSENT;

                /* TODO: parse SDP from the media file rather than hardcoding it */
                sent = rtsp_describe(&rtspmsg, sendbuf);
                send_all(i, sendbuf, sent);
                streamclient.state = SDPSENT;
              }
              break;

            case SDPSENT:
              if (rtspmsg.type == SETUP) {
                sent = rtsp_setup(&rtspmsg, sendbuf, 50508, 50509);
                send_all(i, sendbuf, sent);
                write_remote_ip(tempstr, streamclient.rtspfd);
                resolve_host(tempstr, rtspmsg.clirtpport, 0, SOCK_DGRAM, &info); 
                streamclient.videofds[0] = client_socket(info, 50508);
                resolve_host(tempstr, rtspmsg.clirtcpport, 0, SOCK_DGRAM, &info);
                streamclient.videofds[1] = client_socket(info, 50509);
                streamclient.state = SETUPSENT;
              }
              break;

            case SETUPSENT:
              if (rtspmsg.type == PLAY) {
              }
              
              break;

            default:
              break;
          }
        }
      }
      if (nready <= 0) break;   
    }

  }


  return 1;
}
Пример #9
0
int settings_parse(JsonNode *root) {
    int have_error = 0;

#ifdef WEBSERVER
    int web_port = 0;
    int own_port = 0;

    char *webgui_tpl = malloc(strlen(WEBGUI_TEMPLATE)+1);
    if(!webgui_tpl) {
        logprintf(LOG_ERR, "out of memory");
        exit(EXIT_FAILURE);
    }
    strcpy(webgui_tpl, WEBGUI_TEMPLATE);
    char *webgui_root = malloc(strlen(WEBSERVER_ROOT)+1);
    if(!webgui_root) {
        logprintf(LOG_ERR, "out of memory");
        exit(EXIT_FAILURE);
    }
    strcpy(webgui_root, WEBSERVER_ROOT);
#endif

#ifndef __FreeBSD__
    regex_t regex;
    int reti;
#endif

    JsonNode *jsettings = json_first_child(root);

    while(jsettings) {
        if(strcmp(jsettings->key, "port") == 0
                || strcmp(jsettings->key, "send-repeats") == 0
                || strcmp(jsettings->key, "receive-repeats") == 0) {
            if((int)jsettings->number_ == 0) {
                logprintf(LOG_ERR, "setting \"%s\" must contain a number larger than 0", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
#ifdef WEBSERVER
                if(strcmp(jsettings->key, "port") == 0) {
                    own_port = (int)jsettings->number_;
                }
#endif
                settings_add_number(jsettings->key, (int)jsettings->number_);
            }
        } else if(strcmp(jsettings->key, "standalone") == 0) {
            if(jsettings->number_ < 0 || jsettings->number_ > 1) {
                logprintf(LOG_ERR, "setting \"%s\" must be either 0 or 1", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
                settings_add_number(jsettings->key, (int)jsettings->number_);
            }
        }  else if(strcmp(jsettings->key, "firmware-update") == 0) {
            if(jsettings->number_ < 0 || jsettings->number_ > 1) {
                logprintf(LOG_ERR, "setting \"%s\" must be either 0 or 1", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
                settings_add_number(jsettings->key, (int)jsettings->number_);
            }
        } else if(strcmp(jsettings->key, "log-level") == 0) {
            if((int)jsettings->number_ < 0 || (int)jsettings->number_ > 5) {
                logprintf(LOG_ERR, "setting \"%s\" must contain a number from 0 till 5", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
                settings_add_number(jsettings->key, (int)jsettings->number_);
            }
        } else if(strcmp(jsettings->key, "pid-file") == 0 || strcmp(jsettings->key, "log-file") == 0) {
            if(!jsettings->string_) {
                logprintf(LOG_ERR, "setting \"%s\" must contain an existing file path", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
                if(path_exists(jsettings->string_) != EXIT_SUCCESS) {
                    logprintf(LOG_ERR, "setting \"%s\" must point to an existing folder", jsettings->key);
                    have_error = 1;
                    goto clear;
                } else {
                    settings_add_string(jsettings->key, jsettings->string_);
                }
            }
        } else if(strcmp(jsettings->key, "config-file") == 0 || strcmp(jsettings->key, "hardware-file") == 0) {
            if(!jsettings->string_) {
                logprintf(LOG_ERR, "setting \"%s\" must contain an existing file path", jsettings->key);
                have_error = 1;
                goto clear;
            } else if(strlen(jsettings->string_) > 0) {
                if(settings_file_exists(jsettings->string_) == EXIT_SUCCESS) {
                    settings_add_string(jsettings->key, jsettings->string_);
                } else {
                    logprintf(LOG_ERR, "setting \"%s\" must point to an existing file", jsettings->key);
                    have_error = 1;
                    goto clear;
                }
            }
        } else if(strcmp(jsettings->key, "whitelist") == 0) {
            if(!jsettings->string_) {
                logprintf(LOG_ERR, "setting \"%s\" must contain valid ip addresses", jsettings->key);
                have_error = 1;
                goto clear;
            } else if(strlen(jsettings->string_) > 0) {
#ifndef __FreeBSD__
                char validate[] = "^((\\*|[0-9]|[1-9][0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\\.(\\*|[0-9]|[1-9][0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\\.(\\*|[0-9]|[1-9][0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))\\.(\\*|[0-9]|[1-9][0-9]|1[0-9][0-9]|2([0-4][0-9]|5[0-5]))(,[\\ ]|,|$))+$";
                reti = regcomp(&regex, validate, REG_EXTENDED);
                if(reti) {
                    logprintf(LOG_ERR, "could not compile regex");
                    have_error = 1;
                    goto clear;
                }
                reti = regexec(&regex, jsettings->string_, 0, NULL, 0);
                if(reti == REG_NOMATCH || reti != 0) {
                    logprintf(LOG_ERR, "setting \"%s\" must contain valid ip addresses", jsettings->key);
                    have_error = 1;
                    regfree(&regex);
                    goto clear;
                }
                regfree(&regex);
#endif
                int l = (int)strlen(jsettings->string_)-1;
                if(jsettings->string_[l] == ' ' || jsettings->string_[l] == ',') {
                    logprintf(LOG_ERR, "setting \"%s\" must contain valid ip addresses", jsettings->key);
                    have_error = 1;
                    goto clear;
                }
                settings_add_string(jsettings->key, jsettings->string_);
            }
#ifdef WEBSERVER
        } else if(strcmp(jsettings->key, "webserver-port") == 0) {
            if(jsettings->number_ < 0) {
                logprintf(LOG_ERR, "setting \"%s\" must contain a number larger than 0", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
                web_port = (int)jsettings->number_;
                settings_add_number(jsettings->key, (int)jsettings->number_);
            }
        } else if(strcmp(jsettings->key, "webserver-root") == 0) {
            if(!jsettings->string_ || path_exists(jsettings->string_) != 0) {
                logprintf(LOG_ERR, "setting \"%s\" must contain a valid path", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
                webgui_root = realloc(webgui_root, strlen(jsettings->string_)+1);
                if(!webgui_root) {
                    logprintf(LOG_ERR, "out of memory");
                    exit(EXIT_FAILURE);
                }
                strcpy(webgui_root, jsettings->string_);
                settings_add_string(jsettings->key, jsettings->string_);
            }
        } else if(strcmp(jsettings->key, "webserver-enable") == 0) {
            if(jsettings->number_ < 0 || jsettings->number_ > 1) {
                logprintf(LOG_ERR, "setting \"%s\" must be either 0 or 1", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
                settings_add_number(jsettings->key, (int)jsettings->number_);
            }
        } else if(strcmp(jsettings->key, "webserver-cache") == 0) {
            if(jsettings->number_ < 0 || jsettings->number_ > 1) {
                logprintf(LOG_ERR, "setting \"%s\" must be either 0 or 1", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
                settings_add_number(jsettings->key, (int)jsettings->number_);
            }
        } else if(strcmp(jsettings->key, "webserver-user") == 0) {
            if(jsettings->string_ || strlen(jsettings->string_) > 0) {
                if(name2uid(jsettings->string_) == -1) {
                    logprintf(LOG_ERR, "setting \"%s\" must contain a valid system user", jsettings->key);
                    have_error = 1;
                    goto clear;
                } else {
                    settings_add_string(jsettings->key, jsettings->string_);
                }
            }
        } else if(strcmp(jsettings->key, "webserver-authentication") == 0 && jsettings->tag == JSON_ARRAY) {
            JsonNode *jtmp = json_first_child(jsettings);
            unsigned short i = 0;
            while(jtmp) {
                i++;
                if(jtmp->tag == JSON_STRING) {
                    if(i == 1) {
                        settings_add_string("webserver-authentication-username", jtmp->string_);
                    } else if(i == 2) {
                        settings_add_string("webserver-authentication-password", jtmp->string_);
                    }
                } else {
                    have_error = 1;
                    break;
                }
                if(i > 2) {
                    have_error = 1;
                    break;
                }
                jtmp = jtmp->next;
            }
            if(i != 2 || have_error == 1) {
                logprintf(LOG_ERR, "setting \"%s\" must be in the format of [ \"username\", \"password\" ]", jsettings->key);
                have_error = 1;
                goto clear;
            }
        }  else if(strcmp(jsettings->key, "webgui-template") == 0) {
            if(!jsettings->string_) {
                logprintf(LOG_ERR, "setting \"%s\" must be a valid template", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
                webgui_tpl = realloc(webgui_tpl, strlen(jsettings->string_)+1);
                if(!webgui_tpl) {
                    logprintf(LOG_ERR, "out of memory");
                    exit(EXIT_FAILURE);
                }
                strcpy(webgui_tpl, jsettings->string_);
                settings_add_string(jsettings->key, jsettings->string_);
            }
#endif
#ifdef UPDATE
        } else if(strcmp(jsettings->key, "update-check") == 0) {
            if(jsettings->number_ < 0 || jsettings->number_ > 1) {
                logprintf(LOG_ERR, "setting \"%s\" must be either 0 or 1", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
                settings_add_number(jsettings->key, (int)jsettings->number_);
            }
        } else if(strcmp(jsettings->key, "update-development") == 0) {
            if(jsettings->number_ < 0 || jsettings->number_ > 1) {
                logprintf(LOG_ERR, "setting \"%s\" must be either 0 or 1", jsettings->key);
                have_error = 1;
                goto clear;
            } else {
                settings_add_number(jsettings->key, (int)jsettings->number_);
            }
        } else if(strcmp(jsettings->key, "update-mirror") == 0) {
            char *filename = NULL;
            char *url = NULL;
            char *data = NULL;
            int lg = 0;
            char typebuf[70];

            if(jsettings->string_) {
                url = malloc(strlen(jsettings->string_)+1);
                if(!url) {
                    logprintf(LOG_ERR, "out of memory");
                    exit(EXIT_FAILURE);
                }
                strcpy(url, jsettings->string_);
                http_parse_url(url, &filename);
            }
            if(!jsettings->string_ || http_get(filename, &data, &lg, typebuf) != 200) {
                logprintf(LOG_ERR, "setting \"%s\" must be point to a valid (online) file", jsettings->key);
                /* clean-up http_lib global */
                if(http_server) sfree((void *)&http_server);
                if(filename) sfree((void *)&filename);
                if(url) sfree((void *)&url);
                if(data) sfree((void *)&data);
                have_error = 1;
                goto clear;
            } else {
                settings_add_string(jsettings->key, jsettings->string_);
                /* clean-up http_lib global */
                if(http_server) sfree((void *)&http_server);
                if(filename) sfree((void *)&filename);
                if(url) sfree((void *)&url);
                if(data) sfree((void *)&data);
            }
#endif
        } else {
            logprintf(LOG_ERR, "setting \"%s\" is invalid", jsettings->key);
            have_error = 1;
            goto clear;
        }
        jsettings = jsettings->next;
    }
    json_delete(jsettings);
#ifdef WEBSERVER
    if(webgui_tpl) {
        char *tmp = malloc(strlen(webgui_root)+strlen(webgui_tpl)+13);
        if(!tmp) {
            logprintf(LOG_ERR, "out of memory");
            exit(EXIT_FAILURE);
        }
        sprintf(tmp, "%s/%s/index.html", webgui_root, webgui_tpl);
        if(path_exists(tmp) != EXIT_SUCCESS) {
            logprintf(LOG_ERR, "setting \"webgui-template\", template does not exists");
            have_error = 1;
            sfree((void *)&tmp);
            goto clear;
        }
        sfree((void *)&tmp);
    }

    if(web_port == own_port) {
        logprintf(LOG_ERR, "setting \"port\" and \"webserver-port\" cannot be the same");
        have_error = 1;
        goto clear;
    }
#endif
clear:
#ifdef WEBSERVER
    if(webgui_tpl) {
        sfree((void *)&webgui_tpl);
    }
    if(webgui_root) {
        sfree((void *)&webgui_root);
    }
#endif
    return have_error;
}
Пример #10
0
int
getBlogIDsRakuten(
    const char *userName,       // (I) ユーザ名
    const char *password,       // (I) パスワード
    int        *numberOfBlogs,  // (I) 取得する/取得した blog 情報の数
    BLOGINF    *blogInfo )      // (O) 取得した blog 情報
{
    char    cookie[MAX_COOKIE_LEN];
    char    url[MAX_URLLENGTH];
    int     numOfBlogs = 0;

    cookie[0] = NUL;
    url[0]    = NUL;
    loginRakuten( userName, password, cookie, url );
    if ( url[0] ) {
        size_t  sz = MAX_CONTENT_SIZE;
        char    *response;

        strcpy( blogInfo[0].url, url );
        blogInfo[0].blogName[0] = NUL;
        blogInfo[0].blogID[0]   = NUL;

        response = (char *)malloc( sz );
        if ( response ) {
            setUpReceiveBuffer( response, sz );
            http_get( url, response );
            if ( *response ) {
                char        target[BUFSIZ];
                const char  *p, *q;

                target[0] = NUL;
                p = strstr( response,
                            "<td class=\"title_text\" id=\"title\">" );
                if ( p ) {
                    p += 34;
                    while ( (*p == ' ')  || (*p == '\t') ||
                            (*p == '\r') || (*p == '\n')    )
                        p++;
                    q = strstr( p, "</td>" );
                    if ( q ) {
                        while ( (q > p)                   &&
                                ( (*(q - 1) == ' ')  ||
                                  (*(q - 1) == '\t') ||
                                  (*(q - 1) == '\r') ||
                                  (*(q - 1) == '\n')    )    )
                            q--;
                        strncpy( target, p, q - p );
                        target[q - p] = NUL;
                    }
                }
                else {
                    p = strstr( response, "<title>" );
                    if ( p ) {
                        p += 7;
                        q = strstr( p, sjis2euc(" - 楽天") );
                        if ( q ) {
                            strncpy( target, p, q - p );
                            target[q - p] = NUL;
                        }
                    }
                    else {
                        p = strstr( response, " id=\"counter\">" );
                        if ( p ) {
                            p += 14;
                            p = strstr( p, "<font color=\"" );
                            if ( p ) {
                                p = strchr( p + 13, '>' );
                                if ( p ) {
                                    p++;
                                    q = strstr( p, sjis2euc("&nbsp;  楽天") );
                                    if ( q ) {
                                        strncpy( target, p, q - p );
                                        target[q - p] = NUL;
                                    }
                                }
                            }
                        }
                    }
                }

                if ( target[0] ) {
                    p = euc2sjis( target );
                    strcpy( blogInfo[0].blogName, p ? p : target );
                }
            }

            free( response );
        }

        numOfBlogs = 1;
    }

    *numberOfBlogs = numOfBlogs;

    return ( numOfBlogs );
}
Пример #11
0
/*************************************************************
 * Function:http_post()
 * Arguments:   
 * Description: 
 * Date:
 * Author:
**************************************************************/
int http_post(struct soap *soap, 
              const char *endpoint, const char *host,
              int port,const char *path, const char *action, size_t count)
{
    return http_get( soap ); // http_get
}
Пример #12
0
detect::detect(std::string url, std::string cfgfile) 
{
    try 
    {
        std::map<std::string, std::string> options = get_options(cfgfile);
        std::string json = http_get(options["SERVER"] + 
                                    options["VERSION"] + 
                                    std::string("/detection/detect?url=") + 
                                    url + 
                                    "&api_secret=" + 
                                    options["API_SECRET"] + 
                                    "&api_key=" + 
                                    options["API_KEY"]);
        Json::Reader reader;
        Json::Value root;
        Json::Value faces;
        unsigned int i;

        reader.parse(json, root, false);
        faces = root["face"];
        for (i = 0; i < faces.size(); i++) 
        {
            age_t age;
            age.range = faces[i]["attribute"]["age"]["range"].asUInt();
            age.value = faces[i]["attribute"]["age"]["value"].asUInt();
            
            gender_t gender;
            gender.confidence = faces[i]["attribute"]["gender"]["confidence"].asFloat();
            gender.value = faces[i]["attribute"]["gender"]["value"].asString();
            
            race_t race;
            race.confidence = faces[i]["attribute"]["race"]["confidence"].asFloat();
            race.value = faces[i]["attribute"]["race"]["value"].asString();
            
            attribute_t attribute;
            attribute.age = age;
            attribute.gender = gender;
            attribute.race = race;
            attribute.smiling = faces[i]["attribute"]["smiling"]["value"].asFloat();
            
            face_t face;
            face.attribute = attribute;
            face.face_id = faces[i]["face_id"].asString();
           
            position_t position;
            point_t center;
            center.x = faces[i]["position"]["center"]["x"].asFloat();
            center.y = faces[i]["position"]["center"]["y"].asFloat();
            position.center = center;
            point_t eye_left;
            eye_left.x = faces[i]["position"]["eye_left"]["x"].asFloat();
            eye_left.y = faces[i]["position"]["eye_left"]["y"].asFloat();
            position.eye_left = eye_left;
            point_t eye_right;
            eye_right.x = faces[i]["position"]["eye_right"]["x"].asFloat();
            eye_right.y = faces[i]["position"]["eye_right"]["y"].asFloat();
            position.eye_right = eye_right;
            position.height = faces[i]["position"]["height"].asFloat();
            point_t mouth_left;                                                   
            mouth_left.x = faces[i]["position"]["mouth_left"]["x"].asFloat();          
            mouth_left.y = faces[i]["position"]["mouth_left"]["y"].asFloat();          
            position.mouth_left = mouth_left;
            point_t mouth_right;                                                  
            mouth_right.x = faces[i]["position"]["mouth_right"]["x"].asFloat();        
            mouth_right.y = faces[i]["position"]["mouth_right"]["y"].asFloat();        
            position.mouth_right = mouth_right;
            point_t nose;                                                     
            nose.x = faces[i]["position"]["nose"]["x"].asFloat();           
            nose.y = faces[i]["position"]["nose"]["y"].asFloat();           
            position.nose = nose;
            position.width = faces[i]["position"]["width"].asFloat();
            face.position = position;

            m_faces.push_back(face);
        }
    } 
    catch (std::string ex) 
    {
        std::cout << ex << std::endl;
    }
}
Пример #13
0
Файл: ahttp.c Проект: hfs/afd
/*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ ascp $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/
int
main(int argc, char *argv[])
{
    int   bytes_buffered,
          fd,
          hunk_size;
    off_t bytes_read = 0;
    char  block[1024],
          hostname[45],
          path[MAX_PATH_LENGTH];

    if ((argc != 2) && (argc != 3) && (argc != 4))
    {
        (void)fprintf(stderr, "Usage: %s <filename> [<host> [<path>]]\n", argv[0]);
        exit(-1);
    }
    if (argc == 4)
    {
        (void)strncpy(hostname, argv[2], 44);
        (void)strncpy(path, argv[3], MAX_PATH_LENGTH - 1);
    }
    else if (argc == 3)
    {
        (void)strncpy(hostname, argv[2], 44);
        (void)strcpy(path, "/");
    }
    else
    {
        (void)strcpy(hostname, "localhost");
        (void)strcpy(path, "/");
    }
    if (http_connect(hostname, DEFAULT_HTTP_PORT) == -1)
    {
        (void)fprintf(stderr, "http_connect() failed\n");
        exit(-1);
    }
    if (http_get(hostname, path, argv[1], &bytes_buffered) == INCORRECT)
    {
        (void)fprintf(stderr, "http_get() failed\n");
        exit(-1);
    }
    if ((fd = open(argv[1], (O_WRONLY | O_CREAT | O_TRUNC),
                   (S_IRUSR | S_IWUSR))) == -1)
    {
        (void)fprintf(stderr, "Failed to open() %s : %s\n",
                      argv[1], strerror(errno));
        exit(-1);
    }
    if (bytes_buffered > 0)
    {
        bytes_read += bytes_buffered;
        if (write(fd, msg_str, bytes_buffered) != bytes_buffered)
        {
            (void)fprintf(stderr, "write() error : %s\n", strerror(errno));
            exit(-1);
        }
    }
    while ((hunk_size = http_read(block, 1024)) > 0)
    {
        if (write(fd, block, hunk_size) != hunk_size)
        {
            (void)fprintf(stderr, "write() error : %s\n", strerror(errno));
            exit(-1);
        }
        bytes_read += hunk_size;
    }
    if (close(fd) == -1)
    {
        (void)fprintf(stderr, "close() error : %s\n", strerror(errno));
    }
    (void)fprintf(stdout, "Got file %s with %d Bytes.\n", argv[1], bytes_read);

    return(0);
}
Пример #14
0
/* Yahoo! に login する */
int
loginYahoo(
        const char *username,   // (I)   ユーザ名 (Yahoo! ID)
        const char *password,   // (I)   パスワード
        char       *cookie      // (I/O) クッキー
    )
{
    int     ret   = 0;
    int     retry = 5;
    char    *request;
    char    *response;
    char    url[MAX_URLLENGTH];
    char    challenge[MAX_KEYLENGTH];
    char    u[MAX_KEYLENGTH];
    char    pd[MAX_KEYLENGTH];
    size_t  sz = MAX_CONTENT_SIZE * 4;

    if ( !cookie   ||
         !username || !(*username) ||
         !password || !(*password)    )
         return ( ret );

    request  = (char *)malloc( MAX_CONTENT_SIZE );
    if ( !request ) 
        return ( ret );
    response = (char *)malloc( sz );
    if ( !response ) {
        free( request );
        return ( ret );
    }

    // http://bookmarks.yahoo.com/ を GET
    challenge[0] = NUL;
    u[0]         = NUL;
    pd[0]        = NUL;
    setUpReceiveBuffer( response, sz );
    http_get( "http://bookmarks.yahoo.com/", response );
    if ( *response ) {
        char    *p, *q;

        p = strstr( response, "name=\".challenge\" value=\"" );
        if ( p ) {
            p += 25;
            q = strchr( p, '"' );
            if ( q ) {
                strncpy( challenge, p, q - p );
                challenge[q - p] = NUL;
            }
        }

        p = strstr( response, "name=\".u\" value=\"" );
        if ( p ) {
            p += 17;
            q = strchr( p, '"' );
            if ( q ) {
                strncpy( u, p, q - p );
                u[q - p] = NUL;
            }
        }


        p = strstr( response, "name=\".pd\" value=\"" );
        if ( p ) {
            p += 18;
            q = strchr( p, '"' );
            if ( q ) {
                strncpy( pd, p, q - p );
                pd[q - p] = NUL;
            }
        }
    }

    if ( challenge[0] ) {
        do {
            memset( request,  0x00, MAX_CONTENT_SIZE );

            strcpy( url, "https://login.yahoo.com/config/login?" );
            setTargetURL( url );
            sprintf( request,
                     ".tries=1&"
                     ".src=bmk2&"
                     ".md5=&"
                     ".hash=&"
                     ".js=&"
                     ".last=&"
                     "promo=&"
                     ".intl=us&"
                     ".bypass=&"
                     ".partner=&" );
            if ( u[0] )
                sprintf( request + strlen( request ),
                         ".u=%s&",
                         u );
            else
                sprintf( request + strlen( request ),
                         ".u=&" );
            sprintf( request + strlen( request ),
                     ".v=0&"
                     ".challenge=%s&"
                     ".yplus=&"
                     ".emailCode=&"
                     "pkg=&"
                     "stepid=&"
                     ".ev=&"
                     "hasMsgr=0&"
                     ".chkP=Y&"
                     ".done=%s&",
                     challenge,
                     encodeURL( "http://bookmarks.yahoo.com/" ) );
            if ( pd[0] )
                sprintf( request + strlen( request ),
                         ".pd=%s&",
                         u );
            else
                sprintf( request + strlen( request ),
                         ".pd=&" );
            sprintf( request + strlen( request ),
                     "login=%s&"
                     "passwd=%s&"
                     ".persistent=Y&"
                     ".save=%s",
                     username, password,
                     encodeURL( "Sign In" ) );
            setUpReceiveBuffer( response, sz );
            http_postEx( url, "application/x-www-form-urlencoded",
                         request, response, cookie );

            if ( *response ) {
                char    *p, *q;

                p = strstr( response,
                            "<meta http-equiv=\"Refresh\" content=\"0; url=" );
                if ( p ) {
                    p += 43;
                    q = strchr( p, '"' );
                    if ( q ) {
                        strncpy( url, p, q - p );
                        url[q - p] = NUL;
                        setUpReceiveBuffer( response, sz );
                        http_getEx( url, response, cookie );
                    }
                }

                if ( *response ) {
                    if ( strstr( response, "Sign out</a>" ) != NULL )
                        ret = 1;    /* ログイン成功 */
                    else
                        ret = 0;    /* ログイン失敗 */
                }
            }
            else
                ret = 0;        /* ログイン失敗 */

            if ( ret == 0 ) {
                retry--;
                if ( retry <= 0 )
                    break;
                Sleep( 2000 );
            }
        } while ( ret == 0 );
    }

    free( response );
    free( request  );

    return ( ret );
}
Пример #15
0
Файл: http.c Проект: sjbawpn/c
int main(int argc, char* argv[]) {
    int client_connection;
    char *host, *path;
    struct hostent *host_name;
    struct sockaddr_in host_address;

#ifdef WIN32
    WSDATA wsaData;
#endif

    if (argc < 2) {
        fprintf(stderr, "Usage: %s: <URL>\n", argv[0]);
        return 1;
    }

    if (parse_url(argv[1], &host, &path) == -1) {
        fprintf(stderr, "Error - malformed URL '%s' .\n", argv[1]);
        return 1;
    }

    printf("Connecting to host '%s'\n", host);

    // Step 1 :open a socket connection on http port with the destination host.

#ifdef WIN32
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != NO_ERROR) {
        fprintf(stderr, "ERROR, unable to initialize winsock.\n");
        return 2;
    }
#endif

    client_connection = socket(PF_INET, SOCK_STREAM, 0);

    if (!client_connection) {
        perror("Unable to create local socket");
        return 2;
    }

    host_name = gethostbyname(host);

    if (!host_name) {
        perror( "Error in name resolution");
        return 3;
    }

    host_address.sin_family = AF_INET;
    host_address.sin_port = htons(HTTP_PORT);

    memcpy(&host_address.sin_addr, host_name->h_addr_list[0], sizeof(struct in_addr));

    if (connect(client_connection, (struct sockaddr*) &host_address, sizeof(host_address)) == -1) {
        perror("Unable to connect to host");
        return 4;
    }

    printf("Retrieving document: '%s'\n", path);


    http_get(client_connection, path, host);
    
    display_result(client_connection);

    printf("Shutting down.\n");

#ifdef WIN32
    if (closesocket(client_connection) == -1)
#else
    if (close(client_connection) == -1)
#endif
    {
        perror("Error closing clienet connection");
        return 5;
    }

#ifdef WIN32
    WSACleanup();
#endif

    return 0;
} 
Пример #16
0
int main(int argc,char* argv[]) 
{
	int  ret,lg,blocksize,r,i;
	char typebuf[70];
	char *data=NULL,*filename=NULL,*proxy=NULL;
	int data_len = 0;
	char *type = NULL;
	enum {
		ERR,
		DOPUT,
		DOGET,
		DODEL,
		DOHEA,
		DOPOST
	} todo=ERR;
	
	if (argc!=3) {
		fprintf(stderr,"usage: http <cmd> <url>\n\tby <*****@*****.**>\n");
		return 1;
	}

	i=1;
	 
	if (!strcasecmp(argv[i],"put")) {
		todo=DOPUT;
	} else if (!strcasecmp(argv[i],"get")) {
		todo=DOGET;
	} else if (!strcasecmp(argv[i],"delete")) {
		todo=DODEL;
	} else if (!strcasecmp(argv[i],"head")) {
		todo=DOHEA;
	} else if (!strcasecmp(argv[i],"post")) {
		todo=DOPOST;
	}

	if (todo==ERR) {
		fprintf(stderr,
			"Invalid <cmd> '%s',\nmust be "
			"'put', 'get', 'post', 'delete', or 'head'\n",
			argv[i]
		);
		return 2;
	}

	i++;
	
	if ((proxy=getenv("http_proxy"))) {
		ret=http_proxy_url(proxy);
		if (ret<0) { 
			return ret;
		}
	}
	
	ret=http_parse_url(argv[i],&filename);
	if (ret<0) {
		return ret;
	}
	
	switch (todo) {
	/* *** PUT  *** */
	case DOPUT:
		fprintf(stderr,"reading stdin...\n");
		/* read stdin into memory */
		blocksize=16384;
		lg=0;  

		if (!(data=malloc(blocksize))) {
			return 3;
		}

		while (1) {
			r=read(0,data+lg,blocksize-lg);
			if (r<=0) break; 
			lg+=r;
			if ((3*lg/2)>blocksize) {
				blocksize *= 4;
				fprintf(stderr,
				"read to date: %9d bytes, reallocating buffer to %9d\n",
				lg,blocksize);	
				if (!(data=realloc(data,blocksize))) {
					return 4;
				}
			}
		}

		fprintf(stderr,"read %d bytes\n",lg);
		ret=http_put(filename,data,lg,0,NULL);
		fprintf(stderr,"res=%d\n",ret);
		break;
	/* *** GET  *** */
	case DOGET:
		ret=http_get(filename,&data,&lg,typebuf);
		fprintf(stderr,"res=%d,type='%s',lg=%d\n",ret,typebuf,lg);
		fwrite(data,lg,1,stdout);
		fprintf(stderr, "%s\n", data);
		break;
	/* *** HEAD  *** */
	case DOHEA:
		ret=http_head(filename,&lg,typebuf);
		fprintf(stderr,"res=%d,type='%s',lg=%d\n",ret,typebuf,lg);
		break;
	/* *** DELETE  *** */
	case DODEL:
		ret=http_delete(filename);
		fprintf(stderr,"res=%d\n",ret);
		break;
	case DOPOST:
		ret = http_post(filename, "your_name=1", 11, NULL, &data, &data_len, &type);
		fprintf(stderr,"res=%d\n",ret);
		fprintf(stderr,"%s\n", type);
		fprintf(stderr,"data: %s\n", data);
		break;
	/* impossible... */
	default:
		fprintf(stderr,"impossible todo value=%d\n",todo);
		return 5;
	}
	
	if (type) {
		free(type);
	}

	if (data) {
		 free(data);
	}

	free(filename);
	 
	return ( (ret==201) || (ret==200) ) ? 0 : ret;
}
Пример #17
0
libstocks_return_code download_stocks(char *stocks,
              stock **stock_datas,
              yahoo_source source)
{
  char *stocks_server=NULL;
  char *url_beg=NULL;
  char *url_end=NULL;

  char *url;
  char *data;

  libstocks_return_code error;

#ifdef DEBUG
  printf("*download_stocks\n");
#endif

  switch (source)
    {
    case YAHOO_US:
      stocks_server = (char *)yahoo_us_stocks_server;
      break;

    case YAHOO_EUROPE:
      stocks_server = (char *)yahoo_eu_stocks_server;
      break;
      default:
      stocks_server = (char *)yahoo_us_stocks_server;
    break;

    }

  url_beg = (char *)yahoo_url_beg;
  url_end = (char *)yahoo_url_end;

  url = (char *)malloc(strlen(url_beg)
           +strlen(url_end)
           +strlen(stocks)+1);
  if (url==NULL)
    {
      fprintf(stderr,"Memory allocating error (%s line %d)\n"
        ,__FILE__, __LINE__);
      exit(1);
    }

  strcpy(url, url_beg);
  strcat(url, stocks);
  strcat(url, url_end);

  error=http_get(url, stocks_server, &data);

  free(url);

  if (error) return error;

  *stock_datas = parse_csv_file(data);

  free(data);

  if (!(*stock_datas)) return ERRPCSV;

  return 0;

}
Пример #18
0
static gboolean
dmap_connection_do_something (DMAPConnection * connection)
{
	DMAPConnectionPrivate *priv = connection->priv;
	char *meta;
	char *path;

	g_debug ("Doing something for state: %d", priv->state);

	priv->do_something_id = 0;

	switch (priv->state) {
	case DMAP_GET_INFO:
		g_debug ("Getting DAAP server info");
		if (!http_get
		    (connection, "/server-info", FALSE, 0.0, 0, FALSE,
		     (DMAPResponseHandler) handle_server_info, NULL, FALSE)) {
			g_debug ("Could not get DAAP connection info");
			dmap_connection_state_done (connection, FALSE);
		}
		break;

	case DMAP_GET_PASSWORD:
		if (priv->password_protected) {
			/* FIXME this bit is still synchronous */
			g_debug ("Need a password for %s", priv->name);
			g_free (priv->password);
			priv->password = connection_get_password (connection);

			if (priv->password == NULL
			    || priv->password[0] == '\0') {
				g_debug ("Password entry cancelled");
				priv->result = FALSE;
				priv->state = DMAP_DONE;
				dmap_connection_do_something (connection);
				return FALSE;
			}

			/* If the share went away while we were asking for the password,
			 * don't bother trying to log in.
			 */
			if (priv->state != DMAP_GET_PASSWORD) {
				return FALSE;
			}
		}

		/* otherwise, fall through */
		priv->state = DMAP_LOGIN;

	case DMAP_LOGIN:
		g_debug ("Logging into DAAP server");
		if (!http_get (connection, "/login", FALSE, 0.0, 0, FALSE,
			       (DMAPResponseHandler) handle_login, NULL,
			       FALSE)) {
			g_debug ("Could not login to DAAP server");
			/* FIXME: set state back to GET_PASSWORD to try again */
			dmap_connection_state_done (connection, FALSE);
		}

		break;

	case DMAP_GET_REVISION_NUMBER:
		g_debug ("Getting DAAP server database revision number");
		path = g_strdup_printf
			("/update?session-id=%u&revision-number=1",
			 priv->session_id);
		if (!http_get
		    (connection, path, TRUE, priv->dmap_version, 0, FALSE,
		     (DMAPResponseHandler) handle_update, NULL, FALSE)) {
			g_debug ("Could not get server database revision number");
			dmap_connection_state_done (connection, FALSE);
		}
		g_free (path);
		break;

	case DMAP_GET_DB_INFO:
		g_debug ("Getting DAAP database info");
		path = g_strdup_printf
			("/databases?session-id=%u&revision-number=%d",
			 priv->session_id, priv->revision_number);
		if (!http_get
		    (connection, path, TRUE, priv->dmap_version, 0, FALSE,
		     (DMAPResponseHandler) handle_database_info, NULL,
		     FALSE)) {
			g_debug ("Could not get DAAP database info");
			dmap_connection_state_done (connection, FALSE);
		}
		g_free (path);
		break;

	case DMAP_GET_SONGS:
		g_debug ("Getting DAAP song listing");
		meta = DMAP_CONNECTION_GET_CLASS
			(connection)->get_query_metadata (connection);
		path = g_strdup_printf
			("/databases/%i/items?session-id=%u&revision-number=%i"
			 "&meta=%s", priv->database_id, priv->session_id,
			 priv->revision_number, meta);
		if (!http_get
		    (connection, path, TRUE, priv->dmap_version, 0, FALSE,
		     (DMAPResponseHandler) handle_song_listing, NULL, TRUE)) {
			g_debug ("Could not get DAAP song listing");
			dmap_connection_state_done (connection, FALSE);
		}
		g_free (path);
		g_free (meta);
		break;

	case DMAP_GET_PLAYLISTS:
		g_debug ("Getting DAAP playlists");
		path = g_strdup_printf
			("/databases/%d/containers?session-id=%u&revision-number=%d",
			 priv->database_id, priv->session_id,
			 priv->revision_number);
		if (!http_get
		    (connection, path, TRUE, priv->dmap_version, 0, FALSE,
		     (DMAPResponseHandler) handle_playlists, NULL, TRUE)) {
			g_debug ("Could not get DAAP playlists");
			dmap_connection_state_done (connection, FALSE);
		}
		g_free (path);
		break;

	case DMAP_GET_PLAYLIST_ENTRIES:
		{
			DMAPPlaylist *playlist =
				(DMAPPlaylist *)
				g_slist_nth_data (priv->playlists,
						  priv->reading_playlist);

			g_assert (playlist);
			g_debug ("Reading DAAP playlist %d entries",
				 priv->reading_playlist);
			path = g_strdup_printf
				("/databases/%d/containers/%d/items?session-id=%u&revision-number=%d&meta=dmap.itemid",
				 priv->database_id, playlist->id,
				 priv->session_id, priv->revision_number);
			if (!http_get
			    (connection, path, TRUE, priv->dmap_version, 0,
			     FALSE,
			     (DMAPResponseHandler) handle_playlist_entries,
			     NULL, TRUE)) {
				g_debug ("Could not get entries for DAAP playlist %d", priv->reading_playlist);
				dmap_connection_state_done (connection,
							    FALSE);
			}
			g_free (path);
		}
		break;

	case DMAP_LOGOUT:
		g_debug ("Logging out of DAAP server");
		path = g_strdup_printf ("/logout?session-id=%u",
					priv->session_id);
		if (!http_get
		    (connection, path, TRUE, priv->dmap_version, 0, FALSE,
		     (DMAPResponseHandler) handle_logout, NULL, FALSE)) {
			g_debug ("Could not log out of DAAP server");
			dmap_connection_state_done (connection, FALSE);
		}

		g_free (path);
		break;

	case DMAP_DONE:
		g_debug ("DAAP done");

		dmap_connection_finish (connection);

		break;
	}

	return FALSE;
}
Пример #19
0
int main(int argc, char *argv[])
{
	char *data = NULL;
	char *filename = NULL;
	char typebuf[100];
	int length;
	int http_retcode;

	if (argc < 2) {
		fprintf(stderr, "No url!\n");
		exit(EXIT_FAILURE);
	}

	http_parse_url(argv[1], &filename);
	http_retcode = http_get(filename, &data, &length, typebuf);

	printf ("http_retcode = %d, typebuf = '%s', length = %d\n", http_retcode, typebuf, length);

	switch(http_retcode) {
		case ERRHOST:
			fprintf(stderr, "No such host.\n");
			break;
		case ERRSOCK:
			fprintf(stderr, "Can't create socket.\n");
			break;
		case ERRCONN:
			fprintf(stderr, "Can't connect to host.\n");
			break;
		case ERRWRHD:
			fprintf(stderr, "Write error on socket while writing header.\n");
			break;
		case ERRWRDT:
			fprintf(stderr, "Write error on socket while writing data.\n");
			break;
		case ERRRDHD:
			fprintf(stderr, "Read error on socket while reading result.\n");
			break;
		case ERRPAHD:
			fprintf(stderr, "Invalid answer from data server.\n");
			break;
		case ERRNULL:
			fprintf(stderr, "Null data pointer.\n");
			break;
		case ERRNOLG:
			fprintf(stderr, "No/Bad length in header.\n");
			break;
		case ERRMEM:
			fprintf(stderr, "Can't allocate memory.\n");
			break;
		case ERR400:
			fprintf(stderr, "400: Invalid query.\n");
			break;
		case ERR403:
			fprintf(stderr, "403: Forbidden.\n");
			break;
		case ERR408:
			fprintf(stderr, "408: Request timeout.\n");
			break;
		case ERR500:
			fprintf(stderr, "500: Server error.\n");
			break;
		case ERR501:
			fprintf(stderr, "501: Not implemented.\n");
			break;
		case ERR503:
			fprintf(stderr, "Service overloaded.\n");
			break;
		case OK0:
			fprintf(stderr, "Successfull parse.\n");
			break;
		case OK201:
			fprintf(stderr, "Ressource succesfully created.\n");
			break;
		case OK200:
			fprintf(stderr, "Ressource succesfully read.\n");
			break;
	}

	printf("data: %s\n", data);

/*
	if ((yyin = fopen(argv[1], "r")) == NULL) {
		perror("fopen");
		exit(EXIT_FAILURE);
	}

	yyparse();

	fclose(yyin);
*/

	return 0;

}
Пример #20
0
char *update_package_version(char *mirror) {
	int x = 0;
	size_t l = 0;
	char stable[] = "stable";
	char development[] = "development";
	char *nurl = NULL, *output = NULL, *pch = NULL, line[255], *version = malloc(4);
	int devel = 0;
	memset(line, '\0', 255);
	if(!version) {
		logprintf(LOG_ERR, "out of memory");
		exit(EXIT_FAILURE);
	}

	settings_find_number("update-development", &devel);

	if(devel) {
		nurl = malloc(strlen(mirror)+strlen(development)+41);
		if(!nurl) {
			logprintf(LOG_ERR, "out of memory");
			exit(EXIT_FAILURE);
		}
		sprintf(nurl, "%sdists/%s/main/binary-armhf/Packages.gz", mirror, development);
	} else {
		nurl = malloc(strlen(mirror)+strlen(stable)+41);
		if(!nurl) {
			logprintf(LOG_ERR, "out of memory");
			exit(EXIT_FAILURE);
		}
		sprintf(nurl, "%sdists/%s/main/binary-armhf/Packages.gz", mirror, stable);
	}
	http_parse_url(nurl, &update_filename);
	update_ret = http_get(update_filename, &update_data, &update_lg, update_typebuf);

	strcpy(version, "0.0");

	if(update_ret == 200 && strcmp(update_typebuf, "application/x-gzip") == 0) {
		z_stream strm = {0};
		unsigned char out[0x4000];
		memset(out, '\0', 0x4000);

		strm.zalloc = Z_NULL;
		strm.zfree = Z_NULL;
		strm.opaque = Z_NULL;
		strm.next_in = (unsigned char *)update_data;
		strm.avail_in = (uInt)update_lg;
		strm.next_out = out;
		inflateInit2(&strm, 15 | 32);

		do {
			strm.avail_out = 0x4000;
			inflate(&strm, Z_NO_FLUSH);
			l += strlen((char *)out);
			output = realloc(output, l+1);
			if(!output) {
				logprintf(LOG_ERR, "out of memory");
				exit(EXIT_FAILURE);
			}
			strcpy(&output[l-strlen((char *)out)], (char *)out);
		} while(strm.avail_out == 0);
		inflateEnd(&strm);

		if(output) {
			char *tmp = output;
			x = 0;
			while(*tmp != '\0') {
				if(*tmp == '\n' || *tmp == '\0') {
					if((pch = strstr(line, "Version: ")) > 0) {
						rmsubstr(line, "Version: ");
						rmsubstr(line, "\n");
						if(update_vercmp(line, version) >= 0) {
							version = realloc(version, strlen(line)+1);
							if(!version) {
								logprintf(LOG_ERR, "out of memory");
								exit(EXIT_FAILURE);
							}
							strcpy(version, line);
						}
					}
					memset(line, '\0', 255);
					x=0;
				}
				line[x] = *tmp;
				tmp++;
				x++;
			}
			sfree((void *)&output);
		}
	}
	sfree((void *)&nurl);
	if(update_filename) sfree((void *)&update_filename);
	if(update_data) sfree((void *)&update_data);
	return version;
}
Пример #21
0
/** Initiates a transaction with the auth server, either to authenticate or to
 * update the traffic counters at the server
@param authresponse Returns the information given by the central server 
@param request_type Use the REQUEST_TYPE_* defines in centralserver.h
@param ip IP adress of the client this request is related to
@param mac MAC adress of the client this request is related to
@param token Authentification token of the client
@param incoming Current counter of the client's total incoming traffic, in bytes 
@param outgoing Current counter of the client's total outgoing traffic, in bytes 
*/
t_authcode
auth_server_request(t_authresponse * authresponse, const char *request_type, const char *ip, const char *mac,
                    const char *token, unsigned long long int incoming, unsigned long long int outgoing)
{
    int sockfd;
    char buf[MAX_BUF];
    char *tmp;
    char *safe_token;
    t_auth_serv *auth_server = NULL;
    auth_server = get_auth_server();

    /* Blanket default is error. */
    authresponse->authcode = AUTH_ERROR;

    sockfd = connect_auth_server();

        /**
	 * TODO: XXX change the PHP so we can harmonize stage as request_type
	 * everywhere.
	 */
    memset(buf, 0, sizeof(buf));
    safe_token = httpdUrlEncode(token);
    snprintf(buf, (sizeof(buf) - 1),
             "GET %s%sstage=%s&ip=%s&mac=%s&token=%s&incoming=%llu&outgoing=%llu&gw_id=%s HTTP/1.0\r\n"
             "User-Agent: WiFiDog %s\r\n"
             "Host: %s\r\n"
             "\r\n",
             auth_server->authserv_path,
             auth_server->authserv_auth_script_path_fragment,
             request_type,
             ip,
             mac, safe_token, incoming, outgoing, config_get_config()->gw_id, VERSION, auth_server->authserv_hostname);

    free(safe_token);

    char *res;
#ifdef USE_CYASSL
    if (auth_server->authserv_use_ssl) {
        res = https_get(sockfd, buf, auth_server->authserv_hostname);
    } else {
        res = http_get(sockfd, buf);
    }
#endif
#ifndef USE_CYASSL
    res = http_get(sockfd, buf);
#endif
    if (NULL == res) {
        debug(LOG_ERR, "There was a problem talking to the auth server!");
        return (AUTH_ERROR);
    }

    if ((tmp = strstr(res, "Auth: "))) {
        if (sscanf(tmp, "Auth: %d", (int *)&authresponse->authcode) == 1) {
            debug(LOG_INFO, "Auth server returned authentication code %d", authresponse->authcode);
            free(res);
            return (authresponse->authcode);
        } else {
            debug(LOG_WARNING, "Auth server did not return expected authentication code");
            free(res);
            return (AUTH_ERROR);
        }
    }
    free(res);
    return (AUTH_ERROR);
}
Пример #22
0
ICACHE_FLASH_ATTR
void duckdns_update(void){
    http_get("http://www.duckdns.org/update/mrostudios/e00dada5-2820-493c-9277-e20c8f3ff48d", "", duckdns_response);
}
Пример #23
0
char    *getUsersOfHatenaBookmark( const char *url )
{
    Thread  static char users[32];
    Thread  static char saveURL[MAX_URLLENGTH * 8];
    char    apiURL[MAX_URLLENGTH];
    char    *request;
    char    *response;
    size_t  sz = MAX_CONTENT_SIZE * 16;

    if ( users[0] && (strcmp( users, "(?)" ) != 0 ) )
        if ( !strncmp( url, saveURL, MAX_URLLENGTH - 1 ) )
            return ( users );
    strcpy( users, "(?)" );

    /* XML-RPC API (bookmark.getTotalCount) を実行 */
    request = (char *)malloc( MAX_CONTENT_SIZE );
    if ( !request )
        return ( users );
    response = (char *)malloc( sz );
    if ( !response ) {
        free( request );
        return ( users );
    }

    strcpy( apiURL, "http://b.hatena.ne.jp/xmlrpc" );
    sprintf( request,
             XML_STATEMENT
             "<methodCall>\r\n"
             "<methodName>bookmark.getTotalCount</methodName>\r\n"
             "<params>\r\n"
             "<param>\r\n"
             "<value><string>%s</string></value>\r\n"
             "</param>\r\n"
             "</params>\r\n"
             "</methodCall>",
             url );
    setUpReceiveBuffer( response, sz );
    http_post( apiURL, NULL,
               request, response );
    if ( *response ) {
        char    *p, *q;

        p = strstr( response, "flerror" );
        if ( !p ) {
            // 正常応答
            p = strstr( response, "<value><int>" );
            if ( p ) {
                p += 12;
                q = strstr( p, "</int></value>" );
                if ( q ) {
                    long    num = atol( p );

                    if ( num >= 0 )
                        sprintf( users, "(%d)", num );
                }
            }
        }

        if ( strcmp( users, "(?)" ) != 0 ) {
            free( response );
            free( request );
            return ( users );
        }
    }

    /* Hatena exist API を実行 */
    sprintf( apiURL,
             "http://d.hatena.ne.jp/exist?mode=xml&%s",
             encodeURL( url ) );
    setUpReceiveBuffer( response, sz );
    http_get( apiURL, response );
    if ( *response ) {
        char    *p, *q, *r;

        p = strstr( response, "<count name=\"bookmark\">" );
        if ( p ) {
            p += 23;
            q = strchr( p, '<' );
            if ( q ) {
                char    tmp[32];

                strncpy( tmp, p, q - p );
                tmp[q - p] = NUL;
                sprintf( users, "(%s)", tmp );

                strncpy( saveURL, url, MAX_URLLENGTH - 1 );
                saveURL[MAX_URLLENGTH - 1] = NUL;
            }
        }
        else {
            // エントリページを取得
            //  -- エントリページは getTitle() でも取得しているので、2回も
            //     取得しに行くのはよくない(が、とりあえず、取得しに行く)
            sprintf( apiURL,
                     "http://b.hatena.ne.jp/entry/%s",
                     encodeURLforHatena( url ) );
            setUpReceiveBuffer( response, sz );
            http_get( apiURL, response );
            if ( *response ) {
                p = strstr( response, "<a name=\"comments\"" );
                if ( p ) {
                    int num = 0;

                    p += 18;
                    q = strstr( p, "</a> (" );
                    if ( q ) {
                        p = q + 6;
                        q = strstr(p, "<span class=\"public-count\" title=");
                        if ( q ) {
                            q = strstr( q + 32, "\">" );
                            if ( q )
                                q += 2;
                        }
                        r = strstr( p, ") <a href=\"/entry/" );
                        if ( q && r && (q < r) )
                            num = atol( p ) + atol( q );
                        else if ( r )
                            num = atol( p );
                    }

                    if ( num > 0 ) {
                        sprintf( users, "(%d)", num );

                        strncpy( saveURL, url, MAX_URLLENGTH - 1 );
                        saveURL[MAX_URLLENGTH - 1] = NUL;
                    }
                }
            }
        }
    }

    free( response );
    free( request );

    return ( users );
}
void loop() {
    if(millis() - lastTime > 500UL) {
        lastTime = millis();
        blinkCount++; // time waits for no one!
        if(blinkCount >= 20 && !achievementUnlocked) { // don't poll FB during push ups
            blinkCount = 0;
            uint32_t start = millis();
            char * response = http_get(HOST, PATH);
            if(DEBUG_SERIAL) {
                Serial.print("Time: ");
                Serial.print(millis()-start);
                Serial.println(" ms\r\n");
            }
            ptrStr = strstr(response, "\"likes\":");  // search for string ["likes": ] in response
            if(ptrStr != NULL) // if successful then ptrStr now points at ["likes": ]
            {
                ptrStr += 8; //advance pointer to likes number.
                int x = 0;
                while(x<20 && *ptrStr != ',') {
                    result[x++] = *ptrStr++;
                }
                result[x] = '\0';
                new_likes_val = strtol(result,&ptrEnd,10); // convert string to long int if you need a working number
                if(DEBUG_SERIAL) {
                    Serial.print("Found likes: ");
                    Serial.println(new_likes_val);
                }

                // every time is goes up from the last known highest point,
                // an achievement is unlocked!  This also prevents griefing
                // since it would be very easy to unlike and like over and over.
                if(new_likes_val > old_likes_val) {
                    if(DEBUG_SERIAL) Serial.println("Achievement Unlocked!");
                    old_likes_val = new_likes_val;
                    achievementUnlocked = true;
                }
            }
            else
            {
                if(DEBUG_SERIAL) Serial.println("Likes not found!\n");  // `strstr` returns NULL if search string not found
            }
            // END if(ptrStr != NULL)
        }
        else { // toggle the led while we wait for 10 second mark
            ledState = !ledState;
            digitalWrite(D7, ledState);
        } // END if(blinkCount >= 20 && !achievementUnlocked)
    } // END if(millis() - lastTime > 500UL)

    // If our 'likes' token was matched...
    if(achievementUnlocked) {
        achievementUnlocked = false;

        // Do something special with our servo and the result ;-)
        // This will make our one finger pushup guy point to
        // each digit in the 'likes' value every 700ms, delay for
        // 2 seconds, and then repeat that 3 more times just to
        // make sure you see it.  Then he'll return to a down position.
        uint8_t x;
        uint8_t y = 0;
        while( y++ < 4 ) {
            x = 0; // reset result[] index to point to the first digit
            while( x<20 && result[x] != '\0' ) {
                // scale the current 'likes' digit (0-9) to servoPos's range
                servoPos = map(result[x]-'0',0,9,SERVO_DEG_0,SERVO_DEG_9);
                // tell servo to go to position in variable 'servoPos'
                if(x!=0 && result[x] == result[x-1]) {
                    // if this digit is the same as the last one,
                    // quickly move the pointer down and back up
                    // to help indicate a new digit in the 'likes' number.
                    likeservo.write(map(result[x]-'2',0,9,SERVO_DEG_0,SERVO_DEG_9));
                    delay(200);
                    likeservo.write(servoPos);
                    delay(500);
                }
                else {
                    // else just go to the next 'likes' number in the sequence.
                    likeservo.write(servoPos);
                    delay(700);
                }
                /*
                if(DEBUG_SERIAL) {
                  Serial.print(result[x]-'0');
                  Serial.print(" ");
                  Serial.println(servoPos);
                }
                */
                x++; // increment result[] index to point to the next digit
            }
            delay(2000);
        }
        likeservo.write(0); // Return to down position

    } // END if(achievementUnlocked)
}
Пример #25
0
MyClip  *
getIB( const char *ibID, int *numOfClips )
{
    char    *response;
    char    url[MAX_URLLENGTH];
    char    tmp[BUFSIZ * 2];
    char    *p, *q, *r;
    int     maxNum = MAX_NUMBER_OF_IB;
    int     yyyy, mm, dd, HH, MM, num;
    MyClip  *mp = NULL;
    size_t  sz  = MAX_CONTENT_SIZE * 20;

    *numOfClips = num = 0;
    response = (char *)malloc( sz );
    if ( !response )
        return ( mp );

    sprintf( url, "http://www.blogpeople.net/display/usr/ib/%s.html", ibID );
    setTargetURL( url );
    setUpReceiveBuffer( response, sz );
    p = http_get( url, response );
    if ( !p || !(*p) || !(*response) ) {
        free( response );
        return ( mp );
    }

    mp = (MyClip *)malloc( sizeof ( MyClip ) * maxNum );
    if ( mp ) {
        char    tag[80];
        char    *t = sjis2utf( "title=\"更新日:" );
        int     tlen = strlen( t );

        memset( mp, 0x00, sizeof ( MyClip ) * maxNum );
        p = response;
        tag[0] = NUL;
        while ( *p ) {
            if ( !strncmp( p, "<span class=\"blogpeople-linklist\">", 34 ) ) {
                q = p + 34;
                r = strstr( q, "</span>" );
                if ( r ) {
                    strncpy( tag, q, r - q );
                    tag[r - q] = NUL;
                    p = r + 7;
                }
                else
                    p = q;

                continue;
            }

            if ( !strncmp( p,
                           "<a href=\"http://www.blogpeople.net/cgi-bin/ib_click.cgi?u=http",
                           62 ) ) {
                q = p + 58;
                r = strstr( q, "\" " );
                if ( r ) {
                    strncpy( tmp, q, r - q );
                    tmp[r - q] = NUL;
                    strcpy( mp[num].url, decodeURL( tmp ) );
                    p = r + 2;
                }
                else
                    p = q;

                continue;
            }

            if ( !strncmp( p, t, tlen ) ) {
                q = p + tlen;
                while ( *q && ((*q < '0') || (*q > '9')) )
                    q++;
                yyyy = 2000 + (*q - '0') * 10 + (*(q + 1) - '0');
                q += 2;

                while ( *q && ((*q < '0') || (*q > '9')) )
                    q++;
                mm   = (*q - '0') * 10 + (*(q + 1) - '0');
                q += 2;

                while ( *q && ((*q < '0') || (*q > '9')) )
                    q++;
                dd   = (*q - '0') * 10 + (*(q + 1) - '0');
                q += 2;

                while ( *q && ((*q < '0') || (*q > '9')) )
                    q++;
                HH   = (*q - '0') * 10 + (*(q + 1) - '0');
                q += 2;

                while ( *q && ((*q < '0') || (*q > '9')) )
                    q++;
                MM   = (*q - '0') * 10 + (*(q + 1) - '0');
                q += 2;

                mp[num].yyyy = yyyy;
                mp[num].mm   = mm;
                mp[num].dd   = dd;
                mp[num].HH   = HH;
                mp[num].MM   = MM;
                mp[num].SS   = 0;

                p = q + 20;

                r = strchr( q, '>' );
                if ( r ) {
                    r++;
#ifdef  _DEBUG
                    if ( tag[0] ) {
                        if ( !strstr( tag, "BPIB" ) )
                            strcat( tag, " BPIB" );
                    }
                    else
                        strcpy( tag, "BPIB" );
#endif  /* _DEBUG */
                    strcpy( mp[num].tags, tag );

                    q = strstr( r, "</a>" );
                    if ( q ) {
                        strncpy( mp[num].title, r, q - r );
                        mp[num].title[q - r] = NUL;
                        p = q + 4;
                    }

                    num++;
                    if ( num >= maxNum )
                        break;
                }

                continue;
            }

            p++;
        }
    }

    free( response );
    *numOfClips = num;

    return ( mp );
}
Пример #26
0
/** @internal
 * This function does the actual request.
 */
static void
ping(void)
{
    char request[MAX_BUF];
    FILE *fh;
    int sockfd;
    unsigned long int sys_uptime = 0;
    unsigned int sys_memfree = 0;
    float sys_load = 0;
    t_auth_serv *auth_server = NULL;
    auth_server = get_auth_server();
    static int authdown = 0;

    debug(LOG_DEBUG, "Entering ping()");
    memset(request, 0, sizeof(request));

    /*
     * The ping thread does not really try to see if the auth server is actually
     * working. Merely that there is a web server listening at the port. And that
     * is done by connect_auth_server() internally.
     */
    sockfd = connect_auth_server();
    if (sockfd == -1) {
        /*
         * No auth servers for me to talk to
         */
        if (!authdown) {
            fw_set_authdown();
            authdown = 1;
        }
        return;
    }

    /*
     * Populate uptime, memfree and load
     */
    if ((fh = fopen("/proc/uptime", "r"))) {
        if (fscanf(fh, "%lu", &sys_uptime) != 1)
            debug(LOG_CRIT, "Failed to read uptime");

        fclose(fh);
    }
    if ((fh = fopen("/proc/meminfo", "r"))) {
        while (!feof(fh)) {
            if (fscanf(fh, "MemFree: %u", &sys_memfree) == 0) {
                /* Not on this line */
                while (!feof(fh) && fgetc(fh) != '\n') ;
            } else {
                /* Found it */
                break;
            }
        }
        fclose(fh);
    }
    if ((fh = fopen("/proc/loadavg", "r"))) {
        if (fscanf(fh, "%f", &sys_load) != 1)
            debug(LOG_CRIT, "Failed to read loadavg");

        fclose(fh);
    }

    /*
     * Prep & send request
     */
    snprintf(request, sizeof(request) - 1,
             "GET %s%sgw_id=%s&sys_uptime=%lu&sys_memfree=%u&sys_load=%.2f&wifidog_uptime=%lu&prop=%s&network_id=%s&lat=%s&lon=%s&node_name=%s HTTP/1.0\r\n"
             "User-Agent: WiFiDog-ffw %s\r\n"
             "Host: %s\r\n"
             "\r\n",
             auth_server->authserv_path,
             auth_server->authserv_ping_script_path_fragment,
             config_get_config()->gw_id,
             sys_uptime,
             sys_memfree,
             sys_load,
             (long unsigned int)((long unsigned int)time(NULL) - (long unsigned int)started_time),
             config_get_config()->owner,
             config_get_config()->network,
             config_get_config()->lat,
             config_get_config()->lon,
             config_get_config()->node_name,
             VERSION, auth_server->authserv_hostname);

    char *res;
#ifdef USE_CYASSL
    if (auth_server->authserv_use_ssl) {
        res = https_get(sockfd, request, auth_server->authserv_hostname);
    } else {
        res = http_get(sockfd, request);
    }
#endif
#ifndef USE_CYASSL
    res = http_get(sockfd, request);
#endif
    if (NULL == res) {
        debug(LOG_ERR, "There was a problem pinging the auth server!");
        if (!authdown) {
            fw_set_authdown();
            authdown = 1;
        }
    } else if (strstr(res, "Pong") == 0) {
        debug(LOG_WARNING, "Auth server did NOT say Pong!");
        if (!authdown) {
            fw_set_authdown();
            authdown = 1;
        }
        free(res);
    } else {
        debug(LOG_DEBUG, "Auth Server Says: Pong");
        if (authdown) {
            fw_set_authup();
            authdown = 0;
        }
        free(res);
    }
    return;
}
Пример #27
0
int pkb_update_dns(struct pk_manager* pkm)
{
  int j, len, bogus, rlen;
  struct pk_tunnel* fe_list[1024]; /* Magic, bounded by address_list[] below */
  struct pk_tunnel** fes;
  struct pk_tunnel* fe;
  struct pk_pagekite* kite;
  char printip[128], get_result[10240], *result, *lastup;
  char address_list[1024], payload[2048], signature[2048], url[2048], *alp;

  PK_TRACE_FUNCTION;

  if (time(0) < pkm->last_dns_update + PK_DDNS_UPDATE_INTERVAL_MIN)
    return 0;

  address_list[0] = '\0';
  alp = address_list;

  fes = fe_list;
  *fes = NULL;

  bogus = 0;
  for (j = 0, fe = pkm->tunnels; j < pkm->tunnel_max; j++, fe++) {
    if (fe->ai.ai_addr && fe->fe_hostname && (fe->conn.sockfd >= 0)) {
      if (fe->conn.status & FE_STATUS_WANTED) {
        if (NULL != in_ipaddr_to_str(fe->ai.ai_addr, printip, 128)) {
          len = strlen(printip);
          if (len < 1000-(alp-address_list)) {
            if (alp != address_list) *alp++ = ',';
            strcpy(alp, printip);
            alp += len;
            *fes++ = fe;
            *fes = NULL;
          }
        }
        if (!(fe->conn.status & FE_STATUS_IN_DNS) || pk_state.force_update)
          bogus++;
      }
      else /* Stuff in DNS that shouldn't be also triggers updates */
        if (fe->conn.status & FE_STATUS_IN_DNS) bogus++;
    }
  }
  PK_CHECK_MEMORY_CANARIES;
  if (!bogus) return 0;
  if (!address_list[0]) return 0;

  bogus = 0;
  lastup = "";
  for (j = 0, kite = pkm->kites; j < pkm->kite_max; kite++, j++) {
    if ((kite->protocol[0] != '\0') &&
        (0 != strcasecmp(lastup, kite->public_domain))) {
      PKS_STATE(pkm->status = PK_STATUS_UPDATING_DNS);
      sprintf(payload, "%s:%s", kite->public_domain, address_list);
      pk_sign(NULL, kite->auth_secret, payload, 100, signature);

      sprintf(url, pkm->dynamic_dns_url,
              kite->public_domain, address_list, signature);
      rlen = http_get(url, get_result, 10240);

      if (rlen < 1) {
        pk_log(PK_LOG_MANAGER_ERROR, "DDNS: No response from %s", url);
        bogus++;
      }
      else {
        lastup = kite->public_domain;
        result = skip_http_header(rlen, get_result);
        if ((strncasecmp(result, "nochg", 5) == 0) ||
            (strncasecmp(result, "good", 4) == 0)) {
          pk_log(PK_LOG_MANAGER_INFO, "DDNS: Update OK, %s=%s",
                                      kite->public_domain, address_list);
          for (fes = fe_list; *fes; fes++) {
            (*fes)->last_ddnsup = time(0);
            (*fes)->conn.status |= FE_STATUS_IN_DNS;
          }
        }
        else {
          result[7] = '\0';
          pk_log(PK_LOG_MANAGER_ERROR, "DDNS: Update failed for %s (%s -> %s)",
                                       kite->public_domain, url, result);
          bogus++;
        }
      }
    }
  }

  pkm->last_dns_update = time(0);
  PK_CHECK_MEMORY_CANARIES;
  return bogus;
}
Пример #28
0
/**
 * Simple command-line HTTP client.
 */
int main( int argc, char *argv[ ] )
{
  int client_connection;
  char *host, *path;
  char *proxy_host, *proxy_user, *proxy_password;
  int proxy_port;
  struct hostent *host_name;
  struct sockaddr_in host_address;
  int port = HTTPS_PORT;
  int ind;
  int master_secret_length;
  unsigned char *master_secret;
  int session_id_length;
  unsigned char *session_id;
#ifdef WIN32
  WSADATA wsaData;
#endif

  TLSParameters tls_context;

  if ( argc < 2 )
  {
    fprintf( stderr, 
      "Usage: %s: [-p http://[username:password@]proxy-host:proxy-port] <URL>\n", 
      argv[ 0 ] );
    return 1;
  }

  proxy_host = proxy_user = proxy_password = host = path = session_id = master_secret = NULL;
  session_id_length = master_secret_length = 0;

  for ( ind = 1; ind < ( argc - 1 ); ind++ )
  {
    if ( !strcmp( "-p", argv[ ind ] ) )
    {
      if ( !parse_proxy_param( argv[ ++ind ], &proxy_host, &proxy_port,
                               &proxy_user, &proxy_password ) )
      {
        fprintf( stderr, "Error - malformed proxy parameter '%s'.\n", argv[ 2 ] );
        return 2;
      }
    }
    else if ( !strcmp( "-s", argv[ ind ] ) )
    {
      session_id_length = hex_decode( argv[ ++ind ], &session_id );
    }
    else if ( !strcmp( "-m", argv[ ind ] ) )
    {
      master_secret_length = hex_decode( argv[ ++ind ], &master_secret );
    }
  }

  if ( ( ( master_secret_length > 0 ) && ( session_id_length == 0 ) ) ||
       ( ( master_secret_length == 0 ) && ( session_id_length > 0 ) ) )
  {
    fprintf( stderr, "session id and master secret must both be provided.\n" );
    return 3;
  }

  if ( parse_url( argv[ ind ], &host, &path ) == -1 )
  {
    fprintf( stderr, "Error - malformed URL '%s'.\n", argv[ 1 ] );
    return 1;
  }

  printf( "Connecting to host '%s'\n", host );
  // Step 1: open a socket connection on http port with the destination host.
#ifdef WIN32
  if ( WSAStartup( MAKEWORD( 2, 2 ), &wsaData ) != NO_ERROR )
  {
    fprintf( stderr, "Error, unable to initialize winsock.\n" );
    return 2;
  }
#endif

  client_connection = socket( PF_INET, SOCK_STREAM, 0 );

  if ( !client_connection )
  {
    perror( "Unable to create local socket" );
    return 2;
  }

  if ( proxy_host )
  {
    printf( "Connecting to host '%s'\n", proxy_host );
    host_name = gethostbyname( proxy_host );
  } 
  else
  {
    host_name = gethostbyname( host );
  }

  if ( !host_name )
  {
    perror( "Error in name resolution" );
    return 3;
  }

  host_address.sin_family = AF_INET;
  host_address.sin_port = htons( proxy_host ? proxy_port : HTTPS_PORT  );
  memcpy( &host_address.sin_addr, host_name->h_addr_list[ 0 ], 
          sizeof( struct in_addr ) );

  if ( connect( client_connection, ( struct sockaddr * ) &host_address, 
       sizeof( host_address ) ) == -1 )
  {
    perror( "Unable to connect to host" );
    return 4;
  }

  printf( "Connection complete; negotiating TLS parameters\n" );

  if ( proxy_host )
  {
    if ( !http_connect( client_connection, host, port, proxy_user, 
                        proxy_password ) )
    {
      perror( "Unable to establish proxy tunnel" );
      if ( close( client_connection ) == -1 )
      {
        perror( "Error closing client connection" );
        return 2;
      }
      return 3;
    }
  }

  if ( session_id != NULL )
  {
    if ( tls_resume( client_connection, session_id_length,
         session_id, master_secret, &tls_context ) )
    {
      fprintf( stderr, "Error: unable to negotiate SSL connection.\n" );
      if ( close( client_connection ) == -1 )
      {
        perror( "Error closing client connection" );
        return 2;
      }
      return 3;
    }
  }
  else
  {
    if ( tls_connect( client_connection, &tls_context, 0 ) )
    {
      fprintf( stderr, "Error: unable to negotiate TLS connection.\n" );
      return 3;
    }
  }

  printf( "Retrieving document: '%s'\n", path );
  http_get( client_connection, path, host, &tls_context );

  display_result( client_connection, &tls_context );

  tls_shutdown( client_connection, &tls_context );

  printf( "Session ID was: " );
  show_hex( tls_context.session_id, tls_context.session_id_length );
  printf( "Master secret was: " );
  show_hex( tls_context.master_secret, MASTER_SECRET_LENGTH );

  printf( "Shutting down.\n" );

#ifdef WIN32
  if ( closesocket( client_connection ) == -1 )
#else
  if ( close( client_connection ) == -1 )
#endif
  {
    perror( "Error closing client connection" );
    return 5;
  }

  if ( session_id != NULL )
  {
    free( session_id );
  } 
  
  if ( master_secret != NULL )
  {
    free( master_secret );
  } 

#ifdef WIN32
  WSACleanup();
#endif

  return 0;
}
Пример #29
0
static void ICACHE_FLASH_ATTR poll_timer_callback(void* arg) {
  os_printf("Polling\n");
  http_get("http://coin-op-tshirt.herokuapp.com/simplify/poll", "", poll_http_callback);
}
Пример #30
0
int start_server(const char *url, const char *rtspport)
{
  int mediafd = -1, listenfd, tempfd, maxfd;
  int videofd;
  struct addrinfo *info;
  struct sockaddr_storage remoteaddr;
  socklen_t addrlen = sizeof remoteaddr;
  fd_set readfds, masterfds;
  struct timeval *timeout, *timeind = NULL, timenow;
  int nready, i;
  int videosize, videoleft;
  int recvd, sent;
  char urlhost[URLSIZE], urlpath[URLSIZE], tempstr[URLSIZE];
  unsigned char msgbuf[BUFSIZE], sendbuf[BUFSIZE];
  char *temp;
  unsigned char *sps = NULL, *pps = NULL;
  size_t spslen, ppslen;
  RTSPMsg rtspmsg;
  Client streamclient;
  pthread_t threadid;
  ThreadInfo *tinfo = NULL;

  uint16_t rtpseqno_video = (rand() % 1000000);
  uint16_t rtpseqno_audio = (rand() % 1000000);

  TimeoutEvent *event;

  /* The current state of the protocol */
  int mediastate = IDLE;
  int quit = 0;

  int media_downloaded = 0;

  timeout = (struct timeval *)malloc(sizeof(struct timeval));
  init_client(&streamclient);
  

  /* Open the a file where the video is to be stored */
  if ((videofd = open("videotemp.mp4", O_RDWR | O_CREAT | O_TRUNC, S_IRWXU)) < 0) {
    fatal_error("Error opening the temporary videofile");
  }

  /* Create the RTSP listening socket */
  resolve_host(NULL, rtspport, SOCK_STREAM, AI_PASSIVE, &info);
  listenfd = server_socket(info);
  maxfd = listenfd;


  FD_ZERO(&readfds);
  FD_ZERO(&masterfds);
  FD_SET(listenfd, &masterfds);

  while (!quit) {

    readfds = masterfds;

    if ((nready = Select(maxfd + 1, &readfds, timeind)) == -1) {
      printf("Select interrupted by a signal\n");
    } 

    /* Timeout handling, used for packet pacing and other timeouts */
    else if (nready == 0) {
      timeind = NULL;
      lock_mutex(&queuelock);
      if ((event = pull_event(&queue)) != NULL) {

        switch (event->type) {

	case ENDOFSTREAM:
	  printf("MEDIA FINISHED\n");
	  break;

	case FRAME:
	  /* Video frame */
	  if (event->frame->frametype == VIDEO_FRAME) {
	    rtpseqno_video += send_video_frame(sendbuf, event->frame, streamclient.videofds[0], rtpseqno_video);
	  }

	  /* Audio frame */
	  else {
            rtpseqno_audio += send_audio_frame(sendbuf, event->frame, streamclient.audiofds[0], rtpseqno_audio);
	  }

          free(event->frame->data);
          free(event->frame);
          break;

	case CHECKMEDIASTATE:
	  oma_debug_print("Checking media ready for streaming...\n");
	  if (mediastate != STREAM) {
	    printf("Sending dummy RTP\n");
	    send_dummy_rtp(sendbuf, streamclient.videofds[0], &rtpseqno_video);
	    push_timeout(&queue, 1000, CHECKMEDIASTATE);
	  }
          break;

	default:
	  oma_debug_print("ERRORENOUS EVENT TYPE!\n");
          break;
        }

        /* If there are elements left in the queue, calculate next timeout */
        if (queue.size > 0) {
          *timeout = calculate_delta(&event->time, &queue.first->time);
          timeind = timeout;
          oma_debug_print("Timeout: %ld secs, %ld usecs\n", timeout->tv_sec, timeout->tv_usec);
        }
        else {
          oma_debug_print("The first entry of the queue is NULL!\n");
        }

        if (queue.size < QUEUESIZE / 2) {
          oma_debug_print("Signaling thread to start filling the queue");
          pthread_cond_signal(&queuecond);
        }

        free(event);
      }

      unlock_mutex(&queuelock);
      continue;
    } /* End of timeout handling */

    /* Start to loop through the file descriptors */
    for (i = 0; i <= maxfd; i++) {
      if (FD_ISSET(i, &readfds)) {

        nready--;

        /* New connection from a client */
        if (i == listenfd) {
          oma_debug_print("Recieved a new RTSP connection\n");
	  fflush(stdout);
          if ((tempfd = accept(i, (struct sockaddr *)&remoteaddr, &addrlen)) == -1) {
            if (errno != EWOULDBLOCK && errno != ECONNABORTED &&
                errno != EPROTO && errno != EINTR) {
              fatal_error("accept");
            }
          }

          /* If we are already serving a client, close the new connection. Otherwise, continue. */
          if (streamclient.state != NOCLIENT) {
	    printf("Another RTSP client tried to connect. Sorry, we can only serve one client at a time\n");
	    close (tempfd);
	  }
          else {
            streamclient.rtspfd = tempfd;
            streamclient.state = CLICONNECTED;
            maxfd = max(2, streamclient.rtspfd, maxfd);
            FD_SET(streamclient.rtspfd, &masterfds);
	    }
        }

        /* Data from the media source */
        else if (i == mediafd) {

          switch (mediastate) {

            case GETSENT:
              /* Read ONLY the HTTP message from the socket and store the video size */
              recvd = recv_all(i, msgbuf, BUFSIZE, MSG_PEEK);
              temp = strstr((char *)msgbuf, "\r\n\r\n");
              recvd = recv_all(i, msgbuf, (int)(temp + 4 - (char *)msgbuf), 0);
              printf("Received HTTP response\n%s\n", msgbuf);
              temp = strstr((char *)msgbuf, "Content-Length:");
              sscanf(temp, "Content-Length: %d", &videosize);
              videoleft = videosize;
              mediastate = RECVTCP;
              break;

            case RECVTCP:
              if ((recvd = recv_all(i, msgbuf, BUFSIZE, 0)) == 0) {
                FD_CLR(i, &masterfds);
                close(i);
                oma_debug_print("Socket closed\n");
              }
              oma_debug_print("Received data from video source!\n");

              writestr(videofd, msgbuf, recvd);
              videoleft -= recvd;

              if (videoleft <= 0) {
                
		printf("Video download complete.\n");
                FD_CLR(mediafd, &masterfds);
                close(videofd);
                close(mediafd);
		media_downloaded = 1;
		printf("Media socket closed\n");

                /* Create the context and the queue filler thread parameter struct */
                tinfo = (ThreadInfo *)malloc(sizeof(ThreadInfo));
                initialize_context(&tinfo->ctx, "videotemp.mp4", &tinfo->videoIdx, &tinfo->audioIdx,
                    &tinfo->videoRate, &tinfo->audioRate, &sps, &spslen, &pps, &ppslen);

                /* Launch the queue filler thread */
                CHECK((pthread_create(&threadid, NULL, fill_queue, tinfo)) == 0);
                pthread_detach(threadid);

                /* Send the sprop-parameters before any other frames */
                send_video_frame(sendbuf, create_sprop_frame(sps, spslen, 0),
                    streamclient.videofds[0], rtpseqno_video++);
                send_video_frame(sendbuf, create_sprop_frame(pps, ppslen, 0),
                    streamclient.videofds[0], rtpseqno_video++);

                g_free(sps);
                g_free(pps);

                lock_mutex(&queuelock);
                push_timeout(&queue, 1000, CHECKMEDIASTATE);
                unlock_mutex(&queuelock);

                mediastate = STREAM;
              }
              break;

             case STREAM:
              /*
                 close(videofd);
                 close(mediafd);
                 close(listenfd);
                 quit = 1;
                 */
              break;

            default: 
              break;
          }
        }

        /* Data from a client ( i == streamclient.rtspfd) */
        else {

          oma_debug_print("Received data from rtspfd\n");
	  fflush(stdout);

          if ((recvd = recv_all(i, msgbuf, BUFSIZE, 0)) == 0) {
            FD_CLR(i, &masterfds);
            close(i);
            oma_debug_print("RTSP client closed the connection\n");
            streamclient.state = NOCLIENT;
          }
          else {
            oma_debug_print("%s", msgbuf);
            parse_rtsp(&rtspmsg, msgbuf);
          }

	  if (rtspmsg.type == TEARDOWN) {

            /* Kill thread and empty queue */         
 	    lock_mutex(&queuelock);
            pthread_cancel(threadid);
            empty_queue(&queue);
            sleep(1);
            

	    /* Reply with 200 OK */
            sent = rtsp_teardown(&rtspmsg, sendbuf);
            send_all(i, sendbuf, sent);
            FD_CLR(i, &masterfds);
            close(i);
            close(streamclient.videofds[0]);
            close(streamclient.videofds[1]);
            close(streamclient.audiofds[0]);
            close(streamclient.audiofds[1]);

            printf("Closing AVFormatContext\n");
            close_context(tinfo->ctx);
            free(tinfo);
            rtpseqno_video = (rand() % 1000000) + 7;
            rtpseqno_audio = rtpseqno_video + 9;
            init_client(&streamclient);

	    printf("Closing RTSP client sockets (RTP&RTCP)\n");
            streamclient.state = NOCLIENT;

	    unlock_mutex(&queuelock);
	    pthread_cond_signal(&queuecond);
          }

          switch (streamclient.state) {

            case CLICONNECTED:
              if (rtspmsg.type == OPTIONS) {
                sent = rtsp_options(&rtspmsg, &streamclient, sendbuf);
                send_all(i, sendbuf, sent);
              }
              else if (rtspmsg.type == DESCRIBE) {
		if (media_downloaded == 0) {
		  /* Start fetching the file from the server */
		  parse_url(url, urlhost, urlpath);
		  resolve_host(urlhost, "80", SOCK_STREAM, 0, &info);
		  mediafd = client_socket(info, 0);
		  FD_SET(mediafd, &masterfds);
		  maxfd = max(2, maxfd, mediafd);

		  /* Send the GET message */
		  http_get(url, msgbuf);
		  send_all(mediafd, msgbuf, strlen((char *)msgbuf));
		  mediastate = GETSENT;
		}
		else {
		  mediastate = STREAM;
		}

                /* Send the SDP without sprop-parameter-sets, those are sent
                 * later in-band */
                streamclient.state = SDPSENT;
                sent = rtsp_describe(&streamclient, sendbuf);
                send_all(i, sendbuf, sent);
              }
              break;

            case SDPSENT:
              if (rtspmsg.type == SETUP) {
                streamclient.setupsreceived++;

                /* Open up the needed ports and bind them locally. The RTCP ports opened here
                 * are not really used by this application. */
                write_remote_ip(tempstr, streamclient.rtspfd);
                oma_debug_print("Remote IP: %s\n", tempstr);

                if (streamclient.setupsreceived < 2) {
                  resolve_host(tempstr, rtspmsg.clirtpport, SOCK_DGRAM, 0, &info); 
                  streamclient.audiofds[0] = client_socket(info, streamclient.server_rtp_audio_port);
                  resolve_host(tempstr, rtspmsg.clirtcpport, SOCK_DGRAM, 0, &info);
                  streamclient.audiofds[1] = client_socket(info, streamclient.server_rtcp_audio_port);

                  sent = rtsp_setup(&rtspmsg, &streamclient, sendbuf,
                      streamclient.server_rtp_audio_port, streamclient.server_rtcp_audio_port);

                }
                else {
                  resolve_host(tempstr, rtspmsg.clirtpport, SOCK_DGRAM, 0, &info); 
                  streamclient.videofds[0] = client_socket(info, streamclient.server_rtp_video_port);
                  resolve_host(tempstr, rtspmsg.clirtcpport, SOCK_DGRAM, 0, &info);
                  streamclient.audiofds[1] = client_socket(info, streamclient.server_rtcp_video_port);

                  sent = rtsp_setup(&rtspmsg, &streamclient, sendbuf,
                      streamclient.server_rtp_video_port, streamclient.server_rtcp_video_port);

                streamclient.state = SETUPCOMPLETE;
                }

                oma_debug_print("Sending setup response...\n");
                send_all(i, sendbuf, sent);

              }
              break;

            case SETUPCOMPLETE:
              if (rtspmsg.type == PLAY) {

                /* Respond to the PLAY request, and start sending dummy RTP packets
                 * to disable the client timeout */
                sent = rtsp_play(&rtspmsg, sendbuf);
                send_all(i, sendbuf, sent);

		if (media_downloaded == 0) {
		 
		  lock_mutex(&queuelock);
		  push_timeout(&queue, 100, CHECKMEDIASTATE);
		  unlock_mutex(&queuelock);
		}
		/* Media has already been once downloaded, initialize context and thread */
		else {
		  tinfo = (ThreadInfo *)malloc(sizeof(ThreadInfo));
		  initialize_context(&tinfo->ctx, "videotemp.mp4", &tinfo->videoIdx, &tinfo->audioIdx,
				     &tinfo->videoRate, &tinfo->audioRate, &sps, &spslen, &pps, &ppslen);
		  /* Launch the queue filler thread */
		  CHECK((pthread_create(&threadid, NULL, fill_queue, tinfo)) == 0);
		  pthread_detach(threadid);

		  /* Send the sprop-parameters before any other frames */
		  send_video_frame(sendbuf, create_sprop_frame(sps, spslen, 0),
				   streamclient.videofds[0], rtpseqno_video++);
		  send_video_frame(sendbuf, create_sprop_frame(pps, ppslen, 0),
				   streamclient.videofds[0], rtpseqno_video++);

		  g_free(sps);
		  g_free(pps);

		  /* Dummy timeouts to start queue/timeout mechanism */
		  push_timeout(&queue, 100, CHECKMEDIASTATE);
		  push_timeout(&queue, 2000, CHECKMEDIASTATE);
		}
              }
              
              break;

            default:
              break;
          }
        }
      }

      if (nready <= 0) break;   
    }

    /* Set the timeout value again, since select will mess it up */
    
    lock_mutex(&queuelock);
    if (queue.size > 0) {
      CHECK((gettimeofday(&timenow, NULL)) == 0);
      *timeout = calculate_delta(&timenow, &queue.first->time);
      /* oma_debug_print("Delta sec: %ld, Delta usec: %ld\n", timeout->tv_sec, timeout->tv_usec); */

      if (timeout->tv_sec < 0) {
        timeout->tv_sec = 0;
        timeout->tv_usec = 0;
      }

      timeind = timeout;
    }
    else timeind = NULL;
    unlock_mutex(&queuelock);

  }


  return 1;
}