C client to load binary data to MySQL

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Me Alone

    #1

    C client to load binary data to MySQL

    Hello:

    I am trying to edit some C code I found in "The definitive guide to
    using, programming, and administering MySQL" by Paul DuBois. This C
    client program connects and then segfaults when the function load_image
    is called. Would anyone be able to point me to what I might be doing
    wrong?

    Thanks in advance,
    C Newbie


    #include <mysql/mysql.h>
    #include <stdio.h>

    int load_image(MYSQ L *conn)
    {
    FILE * pic;
    char query[1024*100], buf[1024*10], *p;
    unsigned int from_len;
    int status;

    if ((pic = fopen("./oreilly.gif", "r")) != NULL)
    {
    printf("Open command succeeded\n");
    }
    else
    printf("Open command failed.\n");

    sprintf(query, "INSERT INTO images VALUES (%d,'", 300);
    p = query + strlen(query);
    while ((from_len = fread(buf, 1, sizeof(buf), pic)) 0)
    {
    /* don't overrun end of query buffer! */
    if (p + (2*from_len) + 3 query + sizeof(query))
    {
    fprintf(stderr, "image too big");
    return(1);
    }
    p += mysql_escape_st ring(p, buf, from_len);
    }
    (void) strcpy(p, "')");
    status = mysql_query(con n, query);
    return(status);
    }

    main() {
    MYSQL * mysql;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char *server = "localhost" ;
    char *user = "user";
    char *password = "password";
    char *database = "db";
    unsigned int i;
    char * query = "SELECT * FROM table";
    int fromImage;

    if ((fromImage=loa d_image(mysql)) 0)
    fprintf(stderr, "%d", fromImage);

    if((mysql = mysql_init(NULL )) == NULL)
    {
    fprintf(stderr, "Cannot initialize MySQL");
    exit(1);
    }

    /* Connect to database */
    if (!mysql_real_co nnect(mysql, server,
    user, password, database, 0, NULL, 0))
    {
    fprintf(stderr, "%s\n", mysql_error(mys ql));
    exit(0);
    }

    /* send SQL query */
    if (mysql_real_que ry(mysql, query, strlen(query)))
    {
    fprintf(stderr, "%s\n", mysql_error(mys ql));
    exit(0);
    }

    // Process the result.
    if((res = mysql_store_res ult(mysql)) == NULL)
    {
    fprintf(stderr, "mysql_store_re sult() failed");
    exit(0);
    }

    while ((row = mysql_fetch_row (res)) != NULL)
    {
    for (i = 0; i < mysql_num_field s(res); i++)
    {
    if (i 0)
    fputc ('\t', stdout);
    printf("%s", row[i] != NULL ? row[i] : "NULL");
    }
    fputc ('\n', stdout);
    }

    if (mysql_errno(my sql) != 0)
    fprintf(stderr, "mysql_fetch_ro w() failed");
    else
    printf("%lu rows returned\n", (unsigned long)
    mysql_num_rows( res));

    /* Release memory used to store results and close connection */
    mysql_free_resu lt(res);
    mysql_close(mys ql);
    }
  • Ian Collins

    #2
    Re: C client to load binary data to MySQL

    Me Alone wrote:
    Hello:
    >
    I am trying to edit some C code I found in "The definitive guide to
    using, programming, and administering MySQL" by Paul DuBois. This C
    client program connects and then segfaults when the function load_image
    is called. Would anyone be able to point me to what I might be doing
    wrong?
    >
    Thanks in advance,
    C Newbie
    >
    >
    #include <mysql/mysql.h>
    #include <stdio.h>
    >
    int load_image(MYSQ L *conn)
    {
    FILE * pic;
    char query[1024*100], buf[1024*10], *p;
    These 110K of data may be too big for your environment's stack.

    Otherwise, where exactly does the fault occur?

    --
    Ian Collins.

    Comment

    • Jens Thoms Toerring

      #3
      Re: C client to load binary data to MySQL

      Me Alone <me@home.comwro te:
      I am trying to edit some C code I found in "The definitive guide to
      using, programming, and administering MySQL" by Paul DuBois. This C
      client program connects and then segfaults when the function load_image
      is called. Would anyone be able to point me to what I might be doing
      wrong?
      #include <mysql/mysql.h>
      #include <stdio.h>
      int load_image(MYSQ L *conn)
      {
      FILE * pic;
      char query[1024*100], buf[1024*10], *p;
      unsigned int from_len;
      int status;
      if ((pic = fopen("./oreilly.gif", "r")) != NULL)
      {
      printf("Open command succeeded\n");
      }
      else
      printf("Open command failed.\n");
      Shouldn't you return, indicating failure, when opening the file fails?
      If it failed you will be passing a NULL pointer to fread(). That might
      result in a crash.
      sprintf(query, "INSERT INTO images VALUES (%d,'", 300);
      Why not simply use

      strcpy( query, "INSERT INTO images VALUES (300,'");

      That should do exactly the same.
      p = query + strlen(query);
      while ((from_len = fread(buf, 1, sizeof(buf), pic)) 0)
      {
      /* don't overrun end of query buffer! */
      if (p + (2*from_len) + 3 query + sizeof(query))
      From a nit-picky point of view this is not 100% correct - according
      to the C standard you're only allowed to compare pointers pointing
      witin the same object. But in case 'p + 2 * from_len + 3' is too
      large this expression already points outside of 'query'. In order
      not to violate this constraint you would need to e.g. use a counter
      of how much you already have used of 'query' and compare to that.
      But I don't think that this is the real problem..
      {
      fprintf(stderr, "image too big");
      return(1);
      }
      p += mysql_escape_st ring(p, buf, from_len);
      <OT because not related to C but MySQL>
      The dicumentation recommends to use myqsl_real_esca pe_string() instead.
      </OT>
      }
      (void) strcpy(p, "')");
      Unless you want to use lint or a similar tool te '(void)' bit at the
      start of the line is superfluous.
      status = mysql_query(con n, query);
      This, of course, assumes that 'conn' is a pointer to an open connection
      to the database. I don't know what will happen if you pass it an invalid
      pointer, one thing that could happen is a crash...

      <OT>
      The MySQL documentation explicitely states:
      mysql_query() cannot be used for queries that contain binary data; you
      should use mysql_real_quer y() instead. (Binary data may contain the \0
      character, which mysql_query() interprets as the end of the query string.)
      You should take that into consideration since it's rather likeley that
      what's in a .gif file is binary data.
      </OT>
      return(status);
      }
      main() {
      main() is suposed to return an int. And since you don't pass it arguments
      make that

      int main(void) {
      MYSQL * mysql;
      MYSQL_RES *res;
      MYSQL_ROW row;
      char *server = "localhost" ;
      char *user = "user";
      char *password = "password";
      char *database = "db";
      unsigned int i;
      char * query = "SELECT * FROM table";
      int fromImage;
      if ((fromImage=loa d_image(mysql)) 0)
      fprintf(stderr, "%d", fromImage);
      And here's definitely a problem: you call your function for putting
      the image into the database (load_image() seems to be a mis-nomer for
      what the function does) before you ever opened a connection to it.
      Depending on how mysql_query() handles that case (it probably can't
      since 'mysql' contains some garbage data, not even necessarily NULL
      which it could check for) that might be the most likely reason for
      the segmentation fault.
      Regards, Jens
      --
      \ Jens Thoms Toerring ___ jt@toerring.de
      \______________ ____________ http://toerring.de

      Comment

      • Flash Gordon

        #4
        Re: C client to load binary data to MySQL

        Jens Thoms Toerring wrote:
        Me Alone <me@home.comwro te:
        <snip>
        That should do exactly the same.
        >
        > p = query + strlen(query);
        > while ((from_len = fread(buf, 1, sizeof(buf), pic)) 0)
        > {
        > /* don't overrun end of query buffer! */
        > if (p + (2*from_len) + 3 query + sizeof(query))
        >
        From a nit-picky point of view this is not 100% correct - according
        to the C standard you're only allowed to compare pointers pointing
        witin the same object. But in case 'p + 2 * from_len + 3' is too
        large this expression already points outside of 'query'.
        However, by applying a little algebra we can get a test that does not
        have this problem. Subtract query from both sides of the expression and
        we get:
        if ((p - query) + (2*from_len) + 3 sizeof(query))

        This is valid on any implementation as long as both pointers are in to
        the same object, the difference between them can be represented and we
        don't have anything else causing an arithmetic overflow. Since one is
        unlikely to be constructing a query string anywhere even close to 30000
        characters long I would say this makes it safe for all implementations
        without being any harder to read.
        In order
        not to violate this constraint you would need to e.g. use a counter
        of how much you already have used of 'query' and compare to that.
        But I don't think that this is the real problem..
        I agree with you. However I don't see any good reason to leave this
        unfixed seeing as the fix is so simple.

        <snip>
        > if ((fromImage=loa d_image(mysql)) 0)
        > fprintf(stderr, "%d", fromImage);
        >
        And here's definitely a problem: you call your function for putting
        the image into the database (load_image() seems to be a mis-nomer for
        <snip>

        To the OP, if you need further help with the MySQL parts of this, such
        as the load_image function and connecting to the database, please take
        it to a suitable group, possibly one with mysql or database in its name,
        or the MySQL mailing lists. This group is for discussing C, not the
        myriads of third party libraries which have their own groups and mailing
        lists.
        --
        Flash Gordon

        Comment

        Working...