summaryrefslogtreecommitdiff
path: root/noncore
authorerik <erik>2007-01-24 19:46:19 (UTC)
committer erik <erik>2007-01-24 19:46:19 (UTC)
commita017bf21dd89159052f2f7a3fbc043a24956c08c (patch) (side-by-side diff)
tree008be2b62ee5487dc55b8a7c7f043c94268f8362 /noncore
parenta4a7bd22feb060a80e20c81cded43cc24f5cd423 (diff)
downloadopie-a017bf21dd89159052f2f7a3fbc043a24956c08c.zip
opie-a017bf21dd89159052f2f7a3fbc043a24956c08c.tar.gz
opie-a017bf21dd89159052f2f7a3fbc043a24956c08c.tar.bz2
Every file in this commit has a memory leak of some kind or another. I think
all of them are minor and should not effect properly running code. But if I were you I would give libstocks and the stockticker plugin in Today a wide berth. That library is atrocious.
Diffstat (limited to 'noncore') (more/less context) (ignore whitespace changes)
-rw-r--r--noncore/apps/opie-reader/Bkmks.cpp1
-rw-r--r--noncore/apps/opie-sheet/Excel.cpp4
-rw-r--r--noncore/apps/zsafe/zsafe.cpp57
-rw-r--r--noncore/comm/keypebble/vncauth.c6
-rw-r--r--noncore/net/ftplib/ftplib.c4
-rw-r--r--noncore/todayplugins/stockticker/libstocks/csv.c140
-rw-r--r--noncore/todayplugins/stockticker/libstocks/currency.c1
-rw-r--r--noncore/todayplugins/stockticker/libstocks/lists.h1
-rw-r--r--noncore/todayplugins/stockticker/libstocks/stocks.c189
9 files changed, 246 insertions, 157 deletions
diff --git a/noncore/apps/opie-reader/Bkmks.cpp b/noncore/apps/opie-reader/Bkmks.cpp
index 00141a3..45aa045 100644
--- a/noncore/apps/opie-reader/Bkmks.cpp
+++ b/noncore/apps/opie-reader/Bkmks.cpp
@@ -154,263 +154,264 @@ void Bkmk::setAnno(unsigned char* t, unsigned short len)
{
m_annolen = len;
m_anno = new unsigned char[m_annolen];
memcpy(m_anno, t, m_annolen);
}
else
{
m_annolen = sizeof(tchar);
m_anno = new unsigned char[m_annolen];
*((tchar*)m_anno) = 0;
}
}
void Bkmk::setAnno(tchar* t)
{
if (m_anno != NULL)
{
delete [] m_anno;
m_anno = NULL;
}
if (t != NULL)
{
unsigned short len = ustrlen(t)+1;
m_annolen = sizeof(tchar)*len;
m_anno = new unsigned char[m_annolen];
memcpy(m_anno, t, m_annolen);
}
else
{
m_annolen = sizeof(tchar);
m_anno = new unsigned char[m_annolen];
*((tchar*)m_anno) = 0;
}
}
BkmkFile::BkmkFile(const char *fnm, bool w, bool _x)
:
wt(w), isUpgraded(false), m_extras(_x)
{
if (w)
{
f = fopen(fnm, "wb");
}
else
{
f = fopen(fnm, "rb");
}
}
BkmkFile::~BkmkFile()
{
if (f != NULL) fclose(f);
}
void BkmkFile::write(const Bkmk& b)
{
if (f != NULL)
{
fwrite(&b.m_namelen, sizeof(b.m_namelen),1,f);
fwrite(b.m_name,1,b.m_namelen,f);
fwrite(&b.m_annolen, sizeof(b.m_annolen),1,f);
fwrite(b.m_anno,1,b.m_annolen,f);
fwrite(&b.m_position,sizeof(b.m_position),1,f);
if (m_extras)
{
fwrite(&b.m_position2,sizeof(b.m_position2),1,f);
fwrite(&b.m_red,sizeof(b.m_red),1,f);
fwrite(&b.m_green,sizeof(b.m_green),1,f);
fwrite(&b.m_blue,sizeof(b.m_blue),1,f);
fwrite(&b.m_level,sizeof(b.m_level),1,f);
}
}
}
void BkmkFile::write(CList<Bkmk>& bl)
{
if (f != NULL)
{
fwrite(&magic, sizeof(magic), 1, f);
for (CList<Bkmk>::iterator i = bl.begin(); i != bl.end(); i++)
{
write(*i);
}
}
}
CList<Bkmk>* BkmkFile::readall()
{
CList<Bkmk>* bl = NULL;
if (f != NULL)
{
unsigned long newmagic;
fread(&newmagic, sizeof(newmagic), 1, f);
if ((newmagic & 0xffffff00) != (magic & 0xffffff00))
{
if (QMessageBox::warning(NULL, "Old bookmark file!", "Which version of " PROGNAME "\ndid you upgrade from?", "0_4*", "Any other version") == 0)
{
fseek(f,0,SEEK_SET);
bl = readall00(&read05);
}
else
{
fseek(f,0,SEEK_SET);
bl = readall00(&read03);
}
isUpgraded = true;
}
else
{
switch(newmagic & 0xff)
{
case 7:
isUpgraded = false;
bl = readall00(read07);
// qDebug("Correct version!");
break;
case 6:
isUpgraded = true;
bl = readall00(read06);
// qDebug("Correct version!");
break;
case 5:
isUpgraded = true;
bl = readall00(read05);
// qDebug("Known version!");
break;
default:
// qDebug("Unknown version!");
isUpgraded = true;
bl = readall00(read05);
}
}
}
return bl;
}
CList<Bkmk>* BkmkFile::readall00(Bkmk* (*readfn)(BkmkFile*, FILE*))
{
CList<Bkmk>* bl = new CList<Bkmk>;
while (1)
{
Bkmk* b = (*readfn)(this, f);
if (b == NULL) break;
bl->push_back(*b);
delete b;
}
return bl;
}
Bkmk* BkmkFile::read03(BkmkFile* /*_this*/, FILE* f)
{
Bkmk* b = NULL;
if (f != NULL)
{
unsigned short ln;
if (fread(&ln,sizeof(ln),1,f) == 1)
{
tchar* name = new tchar[ln+1];
fread(name,sizeof(tchar),ln,f);
name[ln] = 0;
ln = 0;
tchar* anno = new tchar[ln+1];
anno[ln] = 0;
unsigned int pos;
fread(&pos,sizeof(pos),1,f);
b = new Bkmk(name,anno,pos);
delete [] anno;
}
}
return b;
}
Bkmk* BkmkFile::read05(BkmkFile* /*_this*/, FILE* f)
{
Bkmk* b = NULL;
if (f != NULL)
{
unsigned short ln;
if (fread(&ln,sizeof(ln),1,f) == 1)
{
tchar* nm = new tchar[ln+1];
fread(nm,sizeof(tchar),ln,f);
nm[ln] = 0;
fread(&ln,sizeof(ln),1,f);
tchar* anno = new tchar[ln+1];
if (ln > 0) fread(anno,sizeof(tchar),ln,f);
anno[ln] = 0;
unsigned int pos;
fread(&pos,sizeof(pos),1,f);
b = new Bkmk(nm,anno,pos);
+ delete [] anno;
}
}
return b;
}
Bkmk* BkmkFile::read06(BkmkFile* /*_this*/, FILE* f)
{
Bkmk* b = NULL;
if (f != NULL)
{
unsigned short ln;
if (fread(&ln,sizeof(ln),1,f) == 1)
{
b = new Bkmk;
b->m_namelen = ln;
b->m_name = new unsigned char[b->m_namelen];
fread(b->m_name,1,b->m_namelen,f);
fread(&(b->m_annolen),sizeof(b->m_annolen),1,f);
if (b->m_annolen > 0)
{
b->m_anno = new unsigned char[b->m_annolen];
fread(b->m_anno,1,b->m_annolen,f);
}
fread(&(b->m_position),sizeof(b->m_position),1,f);
b->m_position2 = b->m_position+b->m_namelen-1;
b->m_red = b->m_green = b->m_blue = 127;
b->m_level = 0;
}
}
return b;
}
Bkmk* BkmkFile::read07(BkmkFile* _this, FILE* f)
{
Bkmk* b = NULL;
if (f != NULL)
{
unsigned short ln;
if (fread(&ln,sizeof(ln),1,f) == 1)
{
b = new Bkmk;
b->m_namelen = ln;
b->m_name = new unsigned char[b->m_namelen];
fread(b->m_name,1,b->m_namelen,f);
fread(&(b->m_annolen),sizeof(b->m_annolen),1,f);
if (b->m_annolen > 0)
{
b->m_anno = new unsigned char[b->m_annolen];
fread(b->m_anno,1,b->m_annolen,f);
}
fread(&(b->m_position),sizeof(b->m_position),1,f);
if (_this->m_extras)
{
fread(&(b->m_position2),sizeof(b->m_position2),1,f);
fread(&(b->m_red),sizeof(b->m_red),1,f);
fread(&(b->m_green),sizeof(b->m_green),1,f);
fread(&(b->m_blue),sizeof(b->m_blue),1,f);
fread(&(b->m_level),sizeof(b->m_level),1,f);
}
else
{
b->m_position2 = b->m_position;
b->m_red = b->m_green = b->m_blue = 255;
b->m_level = 0;
}
}
}
return b;
}
diff --git a/noncore/apps/opie-sheet/Excel.cpp b/noncore/apps/opie-sheet/Excel.cpp
index 51fe707..27080e9 100644
--- a/noncore/apps/opie-sheet/Excel.cpp
+++ b/noncore/apps/opie-sheet/Excel.cpp
@@ -188,385 +188,387 @@ double ExcelBook::Double8Byte(int b1, int b2, int b3, int b4, int b5, int b6, in
ieee[4] = ((int)b4) & 0xff;ieee[5] = ((int)b3) & 0xff;
ieee[6] = ((int)b2) & 0xff;ieee[7] = ((int)b1) & 0xff;
}
else
{
ieee[0] = ((int)b1) & 0xff;ieee[1] = ((int)b2) & 0xff;
ieee[2] = ((int)b3) & 0xff;ieee[3] = ((int)b4) & 0xff;
ieee[4] = ((int)b5) & 0xff;ieee[5] = ((int)b6) & 0xff;
ieee[6] = ((int)b7) & 0xff;ieee[7] = ((int)b8) & 0xff;
}
return d;
};
bool ExcelBook::OpenFile(char *Filename)
{
printf("Opening excel file!\r\n");
File= fopen(Filename, "r");
Position=0; // first byte index in file
XFRecords.resize(0);
SharedStrings.resize(0);
Names.resize(0);
Sheets.resize(0);
if(File==NULL) return false;
printf("Opened excel file!\r\n");
return true;
};
bool ExcelBook::CloseFile(void)
{
int w1;
for(w1=0;w1<(int)XFRecords.count();w1++)
{
if(XFRecords[w1]!=NULL) {delete XFRecords[w1];XFRecords[w1]=NULL;};
};
for(w1=0;w1<(int)SharedStrings.count();w1++)
{
if(SharedStrings[w1]!=NULL) {delete SharedStrings[w1];SharedStrings[w1]=NULL;};
};
for(w1=0;w1<(int)Names.count();w1++)
{
if(Names[w1]!=NULL) {delete Names[w1];Names[w1]=NULL;};
};
for(w1=0;w1<(int)Sheets.count();w1++)
{
if(Sheets[w1]!=NULL) {delete Sheets[w1];Sheets[w1]=NULL;};
};
XFRecords.resize(0);
SharedStrings.resize(0);
Names.resize(0);
Sheets.resize(0);
fclose(File);
printf("closed excel file!\r\n");
if(File==NULL) return true;
return false;
};
void ExcelBook::SeekPosition(int pos)
{
if(!feof(File))
{
Position=pos;
//printf("SeekPosition:Pos:%d\r\n",Position);
fseek(File,pos,SEEK_SET);
};
};
void ExcelBook::SeekSkip(int pos)
{
if(!feof(File))
{
Position=Position+pos;
//printf("SeekSkip:Pos:%d\r\n",Position);
fseek(File, Position, SEEK_SET);
};
};
int ExcelBook::FileEOF(void)
{
if(File!=NULL) return(feof(File)); else return 0;
//EOF is defined in stdlib as -1
};
int ExcelBook::Get2Bytes(void)
{
int i1,i2;
i1=0; i2=0;
if (!feof(File))
{
i1=fgetc(File);
Position++;
};
if (!feof(File))
{
i2=fgetc(File);
Position++;
};
return Integer2Byte(i1,i2);
};
char* ExcelBook::Read(int pos, int length)
{
int i;
char *data;
data= new char[length];
SeekPosition(pos);
for(i=0; i<length; i++)
{
if(!feof(File)) data[i]=fgetc(File);
};
Position= Position+length;
return data;
};
QString ExcelBook::ReadUnicodeChar(int pos, int length)
{
int i;
QString data;
int i1=' ',i2=' ',ii;
SeekPosition(pos);
for(i=0; i<length; i++)
{
if(!feof(File)) i1=fgetc(File);
if(!feof(File)) i2=fgetc(File);
ii=Integer2Byte(i1,i2);
data.append(ii);
Position+=2;
};
return data;
};
QString* ExcelBook::GetString(int num)
{
if(num>=0 && num<(int)SharedStrings.count())
{
return SharedStrings[num];
};
return new QString("");
};
int ExcelBook::SeekBOF(void)
{
int opcode,version,streamtype,length,ret=0;
char *data;
while(!feof(File))
{
opcode=Get2Bytes();
if(opcode==XL_BOF)
{
length=Get2Bytes();
data=Read(Position,length);
version=Integer2Byte(data[0], data[1]);
streamtype=Integer2Byte(data[2], data[3]);
printf("SEEKBOF:opcode=XLBOF, %d ,version %d\r\n",Position,version);
delete [] data; data=NULL;
if (version==BIFF8) ret=8;
else if(version==BIFF7) ret=7;
printf("SEEKBOF:versionBIFF%d\r\n",ret);
if(streamtype==WBKGLOBAL) return ret *2;
else if(streamtype==WRKSHEET) return ret *1;
return 1;
};
};
return 0;
};
ExcelBREC* ExcelBook::GetBREC(void)
{
ExcelBREC* rec;
rec= new ExcelBREC;
if(FileEOF()) return NULL;
rec->data=NULL;
rec->code=Get2Bytes();
rec->length=Get2Bytes();
rec->position=Position;
SeekSkip(rec->length);
return rec;
};
ExcelBREC* ExcelBook::PeekBREC(void)
{
int oldpos;
ExcelBREC* NextRec;
oldpos=Position;
NextRec=GetBREC();
SeekPosition(oldpos);
return NextRec;
};
char* ExcelBook::GetDataOfBREC(ExcelBREC* record)
{
if(record->data==NULL)
{
- ConvertCharToArray(record,Read(record->position,record->length),record->length);
+ char* readData = Read(record->position,record->length);
+ ConvertCharToArray(record,readData,record->length);
+ delete [] readData;
};
return record->data;//new?
};
void ExcelBook::ConvertCharToArray(ExcelBREC* record, char* chars, int length)
{
record->data=new char[length];
for(int w1=0;w1<=length-1;w1++)
record->data[w1]=chars[w1];
};
bool ExcelSheet::InitCells()
{
int r;
Cells.resize(rows * cols + cols+1);
if(Cells.count()==0) return false;
for(r=0;r < Cells.count();r++)
{
Cells[r]=NULL;
};
return true;
};
void ExcelSheet::Set(int row, int col, ExcelCell* cell)
{
if(cell!=NULL&&(row*cols+col)<Cells.count())
{
Cells[row*cols+col]=cell;
};
};
ExcelCell* ExcelSheet::Get(int row, int col)
{
ExcelCell* cell;
cell=Cells[row*cols+col];
if(cell==NULL) return NULL;
return cell;
};
int ExcelBook::SheetHandleRecord(ExcelSheet* sheet, ExcelBREC* record)
{
char* data=NULL;
switch (record->code)
{
case XL_DIMENSION:
data = GetDataOfBREC(record);
if (record->length == 10)
{
sheet->rows = Integer2Byte(data[2], data[3]);
sheet->cols = Integer2Byte(data[6], data[7]);
}
else
{
sheet->rows = Integer4Byte(data[4], data[5], data[6], data[7]);
sheet->cols = Integer2Byte(data[10], data[11]);
}
sheet->InitCells();
break;
case XL_LABELSST:
HandleLabelSST(sheet, record);
break;
case XL_RK:
case XL_RK2:
HandleRK(sheet, record);
break;
case XL_MULRK:
HandleMulrk(sheet, record);
break;
case XL_ROW:
break;
case XL_NUMBER:
HandleNumber(sheet, record);
break;
case XL_BOOLERR:
break;
case XL_CONTINUE:
break;
case XL_FORMULA:
case XL_FORMULA2:
HandleFormula(sheet, record);
break;
case XL_LABEL:
break;
case XL_NAME:
HandleName(sheet, record);
break;
case XL_BOF:
break;
case XL_EOF:
return 0;
default:
break;
};
return 1;
};
int ExcelBook::ReadSheet(ExcelSheet* sheet)
{
ExcelBREC* record;
int oldpos;
oldpos = Position;
SeekPosition(sheet->position);
record = GetBREC();
while (record!=NULL)
{
if (!SheetHandleRecord(sheet, record)) break;
record=GetBREC();
};
SeekPosition(oldpos);
return 1;
};
ExcelSheet* ExcelBook::GetSheet(void)
{
ExcelSheet* sh=NULL;
int type;
type=SeekBOF();
Version=type;
sh=new ExcelSheet;
if(type)
{
sh->type=type;
sh->position=Position;
sh->name=QString("");
};
if(type==8||type==7)
{
ReadSheet(sh);
};
return sh;
};
void ExcelBook::ParseSheets(void)
{
int BOFs;
ExcelBREC* r;
BOFs=1;
r=GetBREC();
while(BOFs)
{
r=GetBREC();
switch(r->code)
{
case XL_SST:
HandleSST(r);
break;
case XL_TXO:
break;
case XL_NAME:
break;
case XL_ROW:
break;
case XL_FORMAT:
HandleFormat(r);
break;
case XL_XF:
HandleXF(r);
break;
case XL_BOUNDSHEET:
HandleBoundSheet(r);
break;
case XL_EXTSST:
break;
case XL_CONTINUE:
break;
case XL_EOF:
BOFs--;
break;
default:
break;
};
};
};
diff --git a/noncore/apps/zsafe/zsafe.cpp b/noncore/apps/zsafe/zsafe.cpp
index f70f863..9c0c6ce 100644
--- a/noncore/apps/zsafe/zsafe.cpp
+++ b/noncore/apps/zsafe/zsafe.cpp
@@ -1579,844 +1579,845 @@ bool ZSafe::openDocument(const char* _filename, const char* )
{
case 1: // No
return false;
break;
case 0: // Yes
newDocument();
return false;
break;
}
}
// load the validation entry
if (validationFlag == 0)
{
pwdOk = 1;
break;
}
retval = loadEntry(entry);
if (retval == 1 &&
!strcmp (entry[0], "ZSAFECATEGORY") &&
!strcmp (entry[1], "name") &&
!strcmp (entry[2], "username") &&
!strcmp (entry[3], "password") &&
!strcmp (entry[4], "comment") )
{
for (int count = 0; count < FIELD_SIZE; count++) free(entry[count]);
pwdOk = 1;
break;
}
else
// for (int count = 0; count < FIELD_SIZE; count++) free(entry[count]);
fclose (fd);
m_password = "";
if (i < numberOfTries - 1)
{
switch( QMessageBox::warning( this, tr("ZSafe"),
tr("Wrong password.\nEnter again?"),
tr("&Yes"), tr("&No."),
0
) )
{
case 1: // No
exitZs (1);
break;
case 0: // Yes
continue;
}
}
}
if (pwdOk == 0)
{
// unset the document entry
conf->writeEntry(APP_KEY+"document", "INVALIDPWD");
if (conf)
delete conf;
exitZs (1);
}
retval = loadEntry(entry);
int numberOfEntries=0;
while (retval == 1) {
QString category( QString::fromUtf8(entry[0]) );
QString name( QString::fromUtf8(entry[1]) );
QString user( QString::fromUtf8(entry[2]) );
QString password( QString::fromUtf8(entry[3]) );
QString comment( QString::fromUtf8(entry[4]) );
QString field5( QString::fromUtf8(entry[5]) );
QString field6( QString::fromUtf8(entry[6]) );
// add the subitems to the categories
Category *cat= categories.find (category);
if (cat)
{
// use the existend item
QListViewItem *catItem = cat->getListItem();
if (catItem)
{
QListViewItem * item = new ShadedListItem( 0, catItem );
item->setText( 0, tr( name ) );
item->setText( 1, tr( user ) );
item->setText( 2, tr( password ) );
item->setText( 3, tr( comment ) );
item->setText( 4, tr( field5 ) );
item->setText( 5, tr( field6 ) );
if (expandTree)
catItem->setOpen( TRUE );
numberOfEntries++;
}
}
else
{
QListViewItem *catI = new ShadedListItem( 1, ListView );
// create and insert a new item
QListViewItem * item = new ShadedListItem( 0, catI );
item->setText( 0, tr( name ) );
item->setText( 1, tr( user ) );
item->setText( 2, tr( password ) );
item->setText( 3, tr( comment ) );
item->setText( 4, tr( field5 ) );
item->setText( 5, tr( field6 ) );
if (expandTree)
catI->setOpen( TRUE );
Category *c1 = new Category();
c1->setCategoryName(category);
QString icon;
QString fullIconPath;
QPixmap *pix;
// #ifndef Q_WS_WIN
icon = conf->readEntry(APP_KEY+category);
// #endif
bool isIconAv = false;
if (!icon.isEmpty() && !icon.isNull())
{
// build the full path
fullIconPath = iconPath + icon;
pix = new QPixmap (fullIconPath);
if (!pix->isNull())
{
QImage img = pix->convertToImage();
pix->convertFromImage(img.smoothScale(14,14));
c1->setIconName (icon);
c1->setIcon (*pix);
isIconAv = true;
}
}
if (!isIconAv)
{
c1->setIcon (*getPredefinedIcon(category));
}
c1->setListItem (catI);
c1->initListItem();
categories.insert (c1->getCategoryName(), c1);
numberOfEntries++;
}
for (int count = 0; count < FIELD_SIZE; count++) {
free(entry[count]);
}
retval = loadEntry(entry);
if (retval == 2) {
// m_parent->slotStatusHelpMsg("Last entry loaded");
}
} // end while
if (numberOfEntries == 0)
{
switch( QMessageBox::warning( this, tr("ZSafe"),
tr("Empty document or\nwrong password.\nContinue?"),
tr("&No"), tr("&Yes."),
0
) ) {
case 0: // No
retval = loadFinalize();
exitZs (1);
break;
case 1: // Yes
break;
}
}
retval = loadFinalize();
return true;
}
int ZSafe::loadInit(const char* _filename, const char *password)
{
unsigned int j = 0;
unsigned int keylength=0;
int count=0, count2=0, count3=0;
unsigned char charbuf[8];
unsigned short ciphertext[4];
char key[128];
Krc2* krc2 = new Krc2();
fd = fopen (_filename, "rb");
- QFileInfo f (_filename);
- load_buffer_length = f.size();
- load_buffer_length = ((load_buffer_length / 1024)+1) * 1024 * 2;
+ QFileInfo f (_filename);
+ load_buffer_length = f.size();
+ load_buffer_length = ((load_buffer_length / 1024)+1) * 1024 * 2;
- if (fd == NULL)
+ if (fd == NULL) {
+ delete krc2;
return PWERR_OPEN;
+ }
buffer = (char *)malloc(load_buffer_length);
for (j = 0; password[j] != '\0'; j++) {
key[j] = password[j];
}
keylength = j;
krc2->rc2_expandkey (key, keylength, 128);
#ifndef Q_WS_WIN
size = read(fileno (fd), (unsigned char *) (charbuf + count), 8);
#else
size = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd);
#endif
- if (size < 8)
+ if (size < 8) {
+ delete krc2;
return PWERR_DATA;
+ }
for (count = 0; count < 4; count++) {
count2 = count << 1;
iv[count] = charbuf[count2] << 8;
iv[count] += charbuf[count2 + 1];
}
size = 0;
bufferIndex = 0;
#ifndef Q_WS_WIN
while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) {
while (count < 8) {
count2 = read (fileno (fd), (unsigned char *) (charbuf + count), 8);
#else
while ((count = fread ((unsigned char *) (charbuf), sizeof(unsigned char), 8, fd)) > 0) {
while (count < 8) {
count2 = fread ((unsigned char *) (charbuf + count), sizeof(unsigned char), 8, fd);
#endif
if (count2 == 0) {
+ delete krc2;
return PWERR_DATA;
}
count += count2;
} /* while (count < 8) */
size += 8;
for (count2 = 0; count2 < 8; count2 += 2) {
count3 = count2 >> 1;
ciphertext[count3] = charbuf[count2] << 8;
ciphertext[count3] += charbuf[count2 + 1];
plaintext[count3] = ciphertext[count3] ^ iv[count3];
iv[count3] = plaintext[count3];
} /* for (count2) */
krc2->rc2_decrypt (plaintext);
memcpy ((unsigned char *) (buffer + bufferIndex), plaintext, 8);
bufferIndex += 8;
buffer[bufferIndex + 1] = '\0';
} /* while ((count = read (fileno (fd), (unsigned char *) charbuf, 8)) > 0) */
+ delete krc2;
size -= buffer[size - 1];
lastcount = 0;
/* This will point to the starting index */
bufferIndex = 0;
return PWERR_GOOD;
}
int ZSafe::loadEntry(char *entry[FIELD_SIZE])
{
/* Strip off PKCS 5 padding
* Should check to make sure it's good here
*/
int count, count1=0;
for (count = lastcount; count < size; count++) {
if ((unsigned char) (buffer[count]) == 255) {
if (buffer[bufferIndex] == '\0') {
bufferIndex++;
}
entry[count1] = (char *) malloc (count - bufferIndex + 1);
memcpy (entry[count1], (unsigned char *) (buffer + bufferIndex), count - bufferIndex);
entry[count1][count - bufferIndex] = '\0';
count++;
bufferIndex = count;
count1++;
if (count1 == FIELD_SIZE) {
lastcount = count;
return 1;
}
} /* if ((unsigned char) (buffer[count]) == 255) */
} /* for (count = 0; count < size; count++) */
return 2;
}
int ZSafe::loadFinalize(void)
{
fclose (fd);
if (buffer) free(buffer);
return PWERR_GOOD;
}
bool ZSafe::saveDocument(const char* _filename,
bool withPwd,
const char* )
{
if (filename.isEmpty())
{
QMessageBox::critical( 0, tr("ZSafe"),
tr("No document defined.\nYou have to create a new document"));
return false;
}
// if (m_password.isEmpty())
// withPwd = true; // the document must be saved with a valid password
if (withPwd)
{
bool pwdOk = FALSE;
while (!pwdOk)
{
getDocPassword(tr("Enter Password"));
if (m_password.isEmpty())
{
QMessageBox::critical( 0, tr("ZSafe"),
tr("Password is empty.\nPlease enter again."));
continue;
}
QString firstPasswd = m_password;
getDocPassword(tr("Reenter Password"));
if (m_password.isEmpty())
{
QMessageBox::critical( 0, tr("ZSafe"),
tr("Password is empty.\nPlease enter again."));
continue;
}
if (firstPasswd != m_password)
{
QMessageBox::critical( 0, tr("ZSafe"),
tr("Passwords must be identical.\nPlease enter again."));
continue;
}
pwdOk = TRUE;
modified = false;
}
}
else if (modified)
{
QString fns(_filename);
fns = fns.right (fns.length() - fns.findRev ('/') - 1);
switch( QMessageBox::information( this, tr("ZSafe"),
tr("Do you want to save ") + fns + tr("\nbefore continuing?"),
tr("&Save"),
tr("&Don't Save"),
0 // Enter == button 0
) )
{ // Escape == button 2
case 0: // Save clicked, Alt-S or Enter pressed.
modified = false;
break;
case 1: // Don't Save clicked or Alt-D pressed
modified = false;
return true;
}
}
modified = false;
if (m_password.isEmpty())
return false;
int retval = saveInit(_filename, m_password);
// int retval = saveInit(_filename, "test");
if (retval != PWERR_GOOD) {
return false;
}
char* entry[FIELD_SIZE];
// save the validation entry
{
int i=0;
entry[i] = (char*)malloc(strlen("ZSAFECATEGORY")+1);
strcpy(entry[i++], "ZSAFECATEGORY");
entry[i] = (char*)malloc(strlen("name")+1);
strcpy(entry[i++], "name");
entry[i] = (char*)malloc(strlen("username")+1);
strcpy(entry[i++], "username");
entry[i] = (char*)malloc(strlen("password")+1);
strcpy(entry[i++], "password");
entry[i] = (char*)malloc(strlen("comment")+1);
strcpy(entry[i++], "comment");
entry[i] = (char*)malloc(strlen("field5")+1);
strcpy(entry[i++], "field5");
entry[i] = (char*)malloc(strlen("field6")+1);
strcpy(entry[i++], "field6");
retval = saveEntry(entry);
for (int z=0; z<i; z++) free(entry[z]);
if (retval == PWERR_DATA) {
#ifndef NO_OPIE
owarn << "1: Error writing file, contents not saved" << oendl;
#else
qWarning("1: Error writing file, contents not saved");
#endif
saveFinalize();
return false;
}
// #ifndef Q_WS_WIN
conf->writeEntry(APP_KEY+"valzsafe", 1);
// #endif
saveConf();
}
QListViewItem *i;
// step through all categories
for (i = ListView->firstChild();
i != NULL;
i = i->nextSibling())
{
// step through all subitems
QListViewItem *si;
for (si = i->firstChild();
si != NULL;
si = si->nextSibling())
{
int j=0;
entry[j] = (char*)malloc(strlen(i->text(0).utf8())+1);
strcpy(entry[j++], i->text(0).utf8());
entry[j] = (char*)malloc(strlen(si->text(0).utf8())+1);
strcpy(entry[j++], si->text(0).utf8());
entry[j] = (char*)malloc(strlen(si->text(1).utf8())+1);
strcpy(entry[j++], si->text(1).utf8());
entry[j] = (char*)malloc(strlen(si->text(2).utf8())+1);
strcpy(entry[j++], si->text(2).utf8());
entry[j] = (char*)malloc(strlen(si->text(3).utf8())+1);
strcpy(entry[j++], si->text(3).utf8());
entry[j] = (char*)malloc(strlen(si->text(4).utf8())+1);
strcpy(entry[j++], si->text(4).utf8());
entry[j] = (char*)malloc(strlen(si->text(5).utf8())+1);
strcpy(entry[j++], si->text(5).utf8());
retval = saveEntry(entry);
for (int z=0; z<j; z++)
{
free(entry[z]);
}
if (retval == PWERR_DATA) {
#ifndef NO_OPIE
owarn << "1: Error writing file, contents not saved" << oendl;
#else
qWarning("1: Error writing file, contents not saved");
#endif
saveFinalize();
return false;
}
}
}
if (saveFinalize() == PWERR_DATA) {
#ifndef NO_OPIE
owarn << "2: Error writing file, contents not saved" << oendl;
#else
qWarning("2: Error writing file, contents not saved");
#endif
return false;
} else {
#ifndef DESKTOP
Global::statusMessage (tr("Password file saved."));
#endif
modified = false;
return true;
}
}
PasswordForm *newPwdDialog;
bool newPwdDialogResult = false;
void ZSafe::setPasswordDialogDone()
{
newPwdDialogResult = true;
newPwdDialog->close();
}
void ZSafe::getDocPassword(QString title)
{
// open the 'Password' dialog
PasswordForm *dialog = new PasswordForm(this, title, TRUE);
newPwdDialog = dialog;
newPwdDialogResult = false;
// QPixmap image0 = Opie::Core::OResource::loadPixmap( "zsafe/zsafe", Opie::Core::OResource::SmallIcon );
// dialog->setIcon( image0);
connect( dialog->PasswordField, SIGNAL( returnPressed() ),
this, SLOT( setPasswordDialogDone() ) );
// CS: !!!
// int pos = filename.findRev ('/');
QString ti = filename.right (filename.length() - filename.findRev ('/') - 1);
dialog->setCaption(ti);
// dialog->setCaption(title);
dialog->PasswordField->setFocus();
QDialog::DialogCode result = (QDialog::DialogCode) dialog->exec();
QString password;
if (result == QDialog::Accepted || newPwdDialogResult)
{
m_password = dialog->PasswordField->text();
}
else
{
exitZs (1);
}
}
int ZSafe::saveInit(const char *_filename, const char *password)
{
char key[128];
unsigned int j = 0;
unsigned int keylength;
// int val;
int count2;
Krc2* krc2 = new Krc2();
- /* first we should check the permissions of the filename */
-/*
- if (QFile::exists(_filename)) {
- val = checkFile(_filename);
- if (val != PWERR_GOOD)
- return val;
- } else
- {
- val = creat (_filename, (S_IRUSR | S_IWUSR));
- if (val == -1)
- return PWERR_OPEN;
- else
- close(val);
- }
-*/
- QFileInfo f (_filename);
- save_buffer_length = f.size();
- save_buffer_length = ((save_buffer_length / 1024)+1) * 1024;
+ QFileInfo f (_filename);
+ save_buffer_length = f.size();
+ save_buffer_length = ((save_buffer_length / 1024)+1) * 1024;
fd = fopen (_filename, "wb");
- if (fd == NULL)
+ if (fd == NULL) {
+ delete krc2;
return PWERR_OPEN;
+ }
buffer = (char*)malloc(save_buffer_length);
/* make the key ready */
for (j = 0; password[j] != '\0'; j++) {
key[j] = password[j];
}
keylength = j;
krc2->rc2_expandkey (key, keylength, 128);
+ delete krc2;
/* First, we make the IV */
for (count2 = 0; count2 < 4; count2++) {
iv[count2] = rand ();
putc ((unsigned char) (iv[count2] >> 8), fd);
putc ((unsigned char) (iv[count2] & 0xff), fd);
}
bufferIndex = 0;
return PWERR_GOOD;
}
int ZSafe::saveEntry(char *entry[FIELD_SIZE])
{
char *text1;
int count2, count3;
unsigned short ciphertext[4];
Krc2* krc2 = new Krc2();
buffer = (char*)memset(buffer, '\0', save_buffer_length);
for (count2 = 0; count2 < FIELD_SIZE; count2++) {
text1 = entry[count2];
if (strlen (text1) == 0) {
strncat(buffer, " ", strlen(" "));
} else {
strncat(buffer, text1, strlen(text1));
}
/* Use 255 as the marker. \n is too tough to test for */
buffer[strlen (buffer)] = 255;
} /*for (count2 = 0; count2 < 5; count2++)*/
count2 = 0;
/* I'm using CBC mode and encrypting the data straight from top down.
* At the bottom, encrypted, I will append an MD5 hash of the file, eventually.
* PKCS 5 padding (explained at the code section
*/
while (count2 < (int)strlen (buffer)) {
#ifndef WORDS_BIGENDIAN
plaintext[bufferIndex] = buffer[count2 + 1] << 8;
plaintext[bufferIndex] += buffer[count2] & 0xff;
#endif
#ifdef WORDS_BIGENDIAN
plaintext[bufferIndex] = buffer[count2] << 8;
plaintext[bufferIndex] += buffer[count2 + 1] & 0xff;
#endif
bufferIndex++;
if (bufferIndex == 4) {
krc2->rc2_encrypt (plaintext);
for (count3 = 0; count3 < 4; count3++) {
ciphertext[count3] = iv[count3] ^ plaintext[count3];
/* Now store the ciphertext as the iv */
iv[count3] = plaintext[count3];
/* reset the buffer index */
bufferIndex = 0;
- if (putc ((unsigned char) (ciphertext[count3] >> 8), fd) == EOF) return PWERR_DATA;
- if (putc ((unsigned char) (ciphertext[count3] & 0xff), fd) == EOF) return PWERR_DATA;
+ if (putc ((unsigned char) (ciphertext[count3] >> 8), fd) == EOF) {
+ delete krc2;
+ return PWERR_DATA;
+ }
+ if (putc ((unsigned char) (ciphertext[count3] & 0xff), fd) == EOF) {
+ delete krc2;
+ return PWERR_DATA;
+ }
} /*for (count3 = 0; count3 < 5; count3++)*/
} /*if (bufferIndex == 5)*/
/* increment a short, not a byte */
count2 += 2;
} /*while (count2 < strlen (buffer))*/
- int ret = PWERR_GOOD;
- return ret;
+ delete krc2;
+ return PWERR_GOOD;
}
int ZSafe::saveFinalize(void)
{
int count1, retval = PWERR_GOOD;
unsigned short ciphertext[4];
Krc2* krc2 = new Krc2();
/* Tack on the PKCS 5 padding
* How it works is we fill up the last n bytes with the value n
*
* So, if we have, say, 13 bytes, 8 of which are used, we have 5 left
* over, leaving us 3 short, so we fill it in with 3's.
*
* If we come out even, we fill it with 8 8s
*
* um, except that in this instance we are using 4 shorts instead of 8 bytes.
* so, half everything
*/
for (count1 = bufferIndex; count1 < 4; count1++) {
plaintext[count1] = (4 - bufferIndex);
}
krc2->rc2_encrypt (plaintext);
for (count1 = 0; count1 < 4; count1++) {
ciphertext[count1] = iv[count1] ^ plaintext[count1];
if (putc ((unsigned char) (ciphertext[count1] >> 8), fd) == EOF) retval = PWERR_DATA;
if (putc ((unsigned char) (ciphertext[count1] & 0xff), fd) == EOF) retval = PWERR_DATA;
}
fclose (fd);
free(buffer);
+ delete krc2;
return retval;
}
void ZSafe::quitMe ()
{
if (modified)
{
switch( QMessageBox::information( this, tr("ZSafe"),
tr("Do you want to save\nbefore exiting?"),
tr("&Save"),
tr("S&ave with\nnew\npassword"),
tr("&Don't Save"),
0 // Enter == button 0
) )
{ // Escape == button 2
case 0: // Save clicked, Alt-S or Enter pressed.
// save
modified = false;
saveDocument(filename, FALSE);
exitZs (1);
break;
case 1: //
// Save with new password
modified = false;
saveDocument(filename, TRUE);
exitZs (1);
break;
case 2: // Don't Save clicked or Alt-D pressed
// don't save but exitZs
exitZs (1);
break;
}
}
exitZs (1);
}
void ZSafe::categoryFieldActivated( const QString& category)
{
if (categoryDialog)
setCategoryDialogFields(categoryDialog, category);
}
void ZSafe::addCategory()
{
if (filename.isEmpty())
{
QMessageBox::critical( 0, tr("ZSafe"),
tr("No document defined.\nYou have to create a new document"));
return;
}
else
{
// open the 'Category' dialog
bool initIcons = false;
// open the 'Category' dialog
CategoryDialog *dialog;
if (categoryDialog)
{
dialog = categoryDialog;
}
else
{
categoryDialog = new CategoryDialog(this, tr("Category"), TRUE);
dialog = categoryDialog;
connect( dialog->CategoryField,
SIGNAL( activated(const QString&)),
this, SLOT( categoryFieldActivated(const QString&) ) );
initIcons = true;
}
// read all categories from the config file and store
// into a list
QFile f (cfgFile);
QStringList list;
if ( f.open(IO_ReadOnly) ) { // file opened successfully
QTextStream t( &f ); // use a text stream
QString s;
while ( !t.eof() ) { // until end of file...
s = t.readLine(); // line of text excluding '\n'
list.append(s);
}
f.close();
}
QStringList::Iterator it = list.begin();
QString categ;
QString firstCategory;
dialog->CategoryField->clear(); // remove all items
while( it != list.end() )
{
QString *cat = new QString (*it);
if (cat->contains("-field1", FALSE))
{
int pos = cat->find ("-field1");
cat->truncate(pos);
categ = *cat;
if (!categ.isEmpty())
{
dialog->CategoryField->insertItem (categ, -1);
if (firstCategory.isEmpty())
firstCategory = categ;
}
}
++it;
}
if (firstCategory.isEmpty())
setCategoryDialogFields(dialog);
else
setCategoryDialogFields(dialog, firstCategory);
// CategoryDialog *dialog = new CategoryDialog(this, "Category", TRUE);
if (initIcons)
{
Wait waitDialog(this, tr("Wait dialog"));
waitDialog.waitLabel->setText(tr("Gathering icons..."));
waitDialog.show();
qApp->processEvents();
QDir d(QPEApplication::qpeDir() + "pics/");
d.setFilter( QDir::Files);
const QFileInfoList *list = d.entryInfoList();
QFileInfoListIterator it( *list ); // create list iterator
QFileInfo *fi; // pointer for traversing
dialog->IconField->insertItem("predefined");
while ( (fi=it.current()) ) { // for each file...
QString fileName = fi->fileName();
if(fileName.right(4) == ".png"){
fileName = fileName.mid(0,fileName.length()-4);
QPixmap imageOfFile(Opie::Core::OResource::loadPixmap(fileName,Opie::Core::OResource::SmallIcon));
dialog->IconField->insertItem(imageOfFile,fileName);
}
++it;
}
waitDialog.hide();
}
QDialog::DialogCode result = (QDialog::DialogCode) dialog->exec();
QString category;
QString icon;
QString fullIconPath;
QPixmap *pix;
if (result == QDialog::Accepted)
{
modified = true;
category = dialog->CategoryField->currentText();
icon = dialog->IconField->currentText()+".png";
QListViewItem *li = new ShadedListItem( 1, ListView );
Category *c1 = new Category();
c1->setCategoryName(category);
// if (!icon.isEmpty() && !icon.isNull())
if (icon != "predefined.png")
{
// build the full path
fullIconPath = iconPath + icon;
pix = new QPixmap (fullIconPath);
// pix->resize(14, 14);
if (!pix->isNull())
{
// save the full pixmap name into the config file
// #ifndef Q_WS_WIN
conf->writeEntry(APP_KEY+category, icon);
// #endif
saveConf();
QImage img = pix->convertToImage();
pix->convertFromImage(img.smoothScale(14,14));
c1->setIcon (*pix);
c1->setIconName(icon);
}
else
{
QPixmap folder( ( const char** ) general_data );
c1->setIcon (folder);
}
}
else
{
c1->setIcon (*getPredefinedIcon(category));
}
c1->setListItem (li);
c1->initListItem();
categories.insert (c1->getCategoryName(), c1);
saveCategoryDialogFields(dialog);
}
diff --git a/noncore/comm/keypebble/vncauth.c b/noncore/comm/keypebble/vncauth.c
index 277d145..7de837a 100644
--- a/noncore/comm/keypebble/vncauth.c
+++ b/noncore/comm/keypebble/vncauth.c
@@ -1,160 +1,164 @@
/*
* Copyright (C) 1997, 1998 Olivetti & Oracle Research Laboratory
*
* This is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*/
/*
* vncauth.c - Functions for VNC password management and authentication.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include "vncauth.h"
#include "d3des.h"
/*
* We use a fixed key to store passwords, since we assume that our local
* file system is secure but nonetheless don't want to store passwords
* as plaintext.
*/
unsigned char fixedkey[8] = {23,82,107,6,35,78,88,7};
/*
* Encrypt a password and store it in a file. Returns 0 if successful,
* 1 if the file could not be written.
*/
int
vncEncryptAndStorePasswd(char *passwd, char *fname)
{
FILE *fp;
uint i;
unsigned char encryptedPasswd[8];
if ((fp = fopen(fname,"w")) == NULL) return 1;
chmod(fname, S_IRUSR|S_IWUSR);
/* pad password with nulls */
for (i = 0; i < 8; i++) {
if (i < strlen(passwd)) {
encryptedPasswd[i] = passwd[i];
} else {
encryptedPasswd[i] = 0;
}
}
/* Do encryption in-place - this way we overwrite our copy of the plaintext
password */
deskey(fixedkey, EN0);
des(encryptedPasswd, encryptedPasswd);
for (i = 0; i < 8; i++) {
putc(encryptedPasswd[i], fp);
}
fclose(fp);
return 0;
}
/*
* Decrypt a password from a file. Returns a pointer to a newly allocated
* string containing the password or a null pointer if the password could
* not be retrieved for some reason.
*/
char *
vncDecryptPasswdFromFile(char *fname)
{
FILE *fp;
int i, ch;
unsigned char *passwd = (unsigned char *)malloc(9);
- if ((fp = fopen(fname,"r")) == NULL) return NULL;
+ if ((fp = fopen(fname,"r")) == NULL) {
+ free(passwd);
+ return NULL;
+ }
for (i = 0; i < 8; i++) {
ch = getc(fp);
if (ch == EOF) {
fclose(fp);
+ free(passwd);
return NULL;
}
passwd[i] = ch;
}
deskey(fixedkey, DE1);
des(passwd, passwd);
passwd[8] = 0;
return (char *)passwd;
}
/*
* Generate CHALLENGESIZE random bytes for use in challenge-response
* authentication.
*/
void
vncRandomBytes(unsigned char *bytes)
{
int i;
unsigned int seed = (unsigned int) time(0);
srandom(seed);
for (i = 0; i < CHALLENGESIZE; i++) {
bytes[i] = (unsigned char)(random() & 255);
}
}
/*
* Encrypt CHALLENGESIZE bytes in memory using a password.
*/
void
vncEncryptBytes(unsigned char *bytes, char *passwd)
{
unsigned char key[8];
int i;
/* key is simply password padded with nulls */
for (i = 0; i < 8; i++) {
if (i < strlen(passwd)) {
key[i] = passwd[i];
} else {
key[i] = 0;
}
}
deskey(key, EN0);
for (i = 0; i < CHALLENGESIZE; i += 8) {
des(bytes+i, bytes+i);
}
}
diff --git a/noncore/net/ftplib/ftplib.c b/noncore/net/ftplib/ftplib.c
index efcd6f0..addf9d2 100644
--- a/noncore/net/ftplib/ftplib.c
+++ b/noncore/net/ftplib/ftplib.c
@@ -983,368 +983,372 @@ GLOBALDEF int FtpWrite(void *buf, int len, netbuf *nData)
GLOBALDEF int FtpClose(netbuf *nData)
{
netbuf *ctrl;
switch (nData->dir)
{
case FTPLIB_WRITE:
/* potential problem - if buffer flush fails, how to notify user? */
if (nData->buf != NULL)
writeline(NULL, 0, nData);
case FTPLIB_READ:
if (nData->buf)
free(nData->buf);
shutdown(nData->handle,2);
net_close(nData->handle);
ctrl = nData->ctrl;
free(nData);
if (ctrl)
{
ctrl->data = NULL;
return(readresp('2', ctrl));
}
return 1;
case FTPLIB_CONTROL:
if (nData->data)
{
nData->ctrl = NULL;
FtpClose(nData);
}
net_close(nData->handle);
free(nData);
return 0;
}
return 1;
}
/*
* FtpSite - send a SITE command
*
* return 1 if command successful, 0 otherwise
*/
GLOBALDEF int FtpSite(const char *cmd, netbuf *nControl)
{
char buf[256];
if ((strlen(cmd) + 7) > sizeof(buf))
return 0;
sprintf(buf,"SITE %s",cmd);
if (!FtpSendCmd(buf,'2',nControl))
return 0;
return 1;
}
/*
* FtpSysType - send a SYST command
*
* Fills in the user buffer with the remote system type. If more
* information from the response is required, the user can parse
* it out of the response buffer returned by FtpLastResponse().
*
* return 1 if command successful, 0 otherwise
*/
GLOBALDEF int FtpSysType(char *buf, int max, netbuf *nControl)
{
int l = max;
char *b = buf;
char *s;
if (!FtpSendCmd("SYST",'2',nControl))
return 0;
s = &nControl->response[4];
while ((--l) && (*s != ' '))
*b++ = *s++;
*b++ = '\0';
return 1;
}
/*
* FtpMkdir - create a directory at server
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpMkdir(const char *path, netbuf *nControl)
{
char buf[256];
if ((strlen(path) + 6) > sizeof(buf))
return 0;
sprintf(buf,"MKD %s",path);
if (!FtpSendCmd(buf,'2', nControl))
return 0;
return 1;
}
/*
* FtpChdir - change path at remote
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpChdir(const char *path, netbuf *nControl)
{
char buf[256];
if ((strlen(path) + 6) > sizeof(buf))
return 0;
sprintf(buf,"CWD %s",path);
if (!FtpSendCmd(buf,'2',nControl))
return 0;
return 1;
}
/*
* FtpCDUp - move to parent directory at remote
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpCDUp(netbuf *nControl)
{
if (!FtpSendCmd("CDUP",'2',nControl))
return 0;
return 1;
}
/*
* FtpRmdir - remove directory at remote
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpRmdir(const char *path, netbuf *nControl)
{
char buf[256];
if ((strlen(path) + 6) > sizeof(buf))
return 0;
sprintf(buf,"RMD %s",path);
if (!FtpSendCmd(buf,'2',nControl))
return 0;
return 1;
}
/*
* FtpPwd - get working directory at remote
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpPwd(char *path, int max, netbuf *nControl)
{
int l = max;
char *b = path;
char *s;
if (!FtpSendCmd("PWD",'2',nControl))
return 0;
s = strchr(nControl->response, '"');
if (s == NULL)
return 0;
s++;
while ((--l) && (*s) && (*s != '"'))
*b++ = *s++;
*b++ = '\0';
return 1;
}
/*
* FtpXfer - issue a command and transfer data
*
* return 1 if successful, 0 otherwise
*/
static int FtpXfer(const char *localfile, const char *path,
netbuf *nControl, int typ, int mode)
{
int l,c;
char *dbuf;
FILE *local = NULL;
netbuf *nData;
int rv=1;
if (localfile != NULL)
{
char ac[4] = "w";
if (typ == FTPLIB_FILE_WRITE)
ac[0] = 'r';
if (mode == FTPLIB_IMAGE)
ac[1] = 'b';
local = fopen(localfile, ac);
if (local == NULL)
{
strncpy(nControl->response, strerror(errno),
sizeof(nControl->response));
return 0;
}
}
if (local == NULL)
local = (typ == FTPLIB_FILE_WRITE) ? stdin : stdout;
if (!FtpAccess(path, typ, mode, nControl, &nData))
+ {
+ if (localfile != NULL)
+ fclose(local);
return 0;
+ }
dbuf = malloc(FTPLIB_BUFSIZ);
if (typ == FTPLIB_FILE_WRITE)
{
while ((l = fread(dbuf, 1, FTPLIB_BUFSIZ, local)) > 0)
if ((c = FtpWrite(dbuf, l, nData)) < l)
{
printf("short write: passed %d, wrote %d\n", l, c);
rv = 0;
break;
}
}
else
{
while ((l = FtpRead(dbuf, FTPLIB_BUFSIZ, nData)) > 0)
if (fwrite(dbuf, 1, l, local) <= 0)
{
perror("localfile write");
rv = 0;
break;
}
}
free(dbuf);
fflush(local);
if (localfile != NULL)
fclose(local);
FtpClose(nData);
return rv;
}
/*
* FtpNlst - issue an NLST command and write response to output
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpNlst(const char *outputfile, const char *path,
netbuf *nControl)
{
return FtpXfer(outputfile, path, nControl, FTPLIB_DIR, FTPLIB_ASCII);
}
/*
* FtpDir - issue a LIST command and write response to output
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpDir(const char *outputfile, const char *path, netbuf *nControl)
{
return FtpXfer(outputfile, path, nControl, FTPLIB_DIR_VERBOSE, FTPLIB_ASCII);
}
/*
* FtpSize - determine the size of a remote file
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpSize(const char *path, int *size, char mode, netbuf *nControl)
{
char cmd[256];
int resp,sz,rv=1;
if ((strlen(path) + 7) > sizeof(cmd))
return 0;
sprintf(cmd, "TYPE %c", mode);
if (!FtpSendCmd(cmd, '2', nControl))
return 0;
sprintf(cmd,"SIZE %s",path);
if (!FtpSendCmd(cmd,'2',nControl))
rv = 0;
else
{
if (sscanf(nControl->response, "%d %d", &resp, &sz) == 2)
*size = sz;
else
rv = 0;
}
return rv;
}
/*
* FtpModDate - determine the modification date of a remote file
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpModDate(const char *path, char *dt, int max, netbuf *nControl)
{
char buf[256];
int rv = 1;
if ((strlen(path) + 7) > sizeof(buf))
return 0;
sprintf(buf,"MDTM %s",path);
if (!FtpSendCmd(buf,'2',nControl))
rv = 0;
else
strncpy(dt, &nControl->response[4], max);
return rv;
}
/*
* FtpGet - issue a GET command and write received data to output
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpGet(const char *outputfile, const char *path,
char mode, netbuf *nControl)
{
return FtpXfer(outputfile, path, nControl, FTPLIB_FILE_READ, mode);
}
/*
* FtpPut - issue a PUT command and send data from input
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpPut(const char *inputfile, const char *path, char mode,
netbuf *nControl)
{
return FtpXfer(inputfile, path, nControl, FTPLIB_FILE_WRITE, mode);
}
/*
* FtpRename - rename a file at remote
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpRename(const char *src, const char *dst, netbuf *nControl)
{
char cmd[256];
if (((strlen(src) + 7) > sizeof(cmd)) ||
((strlen(dst) + 7) > sizeof(cmd)))
return 0;
sprintf(cmd,"RNFR %s",src);
if (!FtpSendCmd(cmd,'3',nControl))
return 0;
sprintf(cmd,"RNTO %s",dst);
if (!FtpSendCmd(cmd,'2',nControl))
return 0;
return 1;
}
/*
* FtpDelete - delete a file at remote
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF int FtpDelete(const char *fnm, netbuf *nControl)
{
char cmd[256];
if ((strlen(fnm) + 7) > sizeof(cmd))
return 0;
sprintf(cmd,"DELE %s",fnm);
if (!FtpSendCmd(cmd,'2', nControl))
return 0;
return 1;
}
/*
* FtpQuit - disconnect from remote
*
* return 1 if successful, 0 otherwise
*/
GLOBALDEF void FtpQuit(netbuf *nControl)
{
if (nControl->dir != FTPLIB_CONTROL)
return;
if (FtpSendCmd("QUIT",'2',nControl) == 1) {
if (ftplib_debug > 2)
fprintf(stderr, "FtpQuit: FtpSendCmd(QUIT) failed\n");
}
net_close(nControl->handle);
free(nControl->buf);
free(nControl);
}
diff --git a/noncore/todayplugins/stockticker/libstocks/csv.c b/noncore/todayplugins/stockticker/libstocks/csv.c
index 86d8607..110df7c 100644
--- a/noncore/todayplugins/stockticker/libstocks/csv.c
+++ b/noncore/todayplugins/stockticker/libstocks/csv.c
@@ -1,406 +1,480 @@
/* libstocks - Library to get current stock quotes from Yahoo Finance
*
* Copyright (C) 2000 Eric Laeuffer
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#define __CSV_C__
#ifndef __UNIX__
#define __UNIX__
#endif
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#ifdef __WINDOWS__
#include <mbstring.h>
#endif
#include "csv.h"
#include "stocks.h"
#include "lists.h"
#define DATE_LENGTH 7 /*YYMMDD*/
const char *months[12]=
{
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
};
/*****************************************************************************/
/* Replacement of the strtok function. This one forgets "delim" when it is */
/* between two commas. */
/* Thanks to Julio Lucas who has told me the bug and has proposed me a patch */
/*****************************************************************************/
char *csv_strtok(char *s, char *delim)
{
static char *next=NULL;
char *temp, *first;
int comma=0;
if (s!=NULL) first=s;
else first=next;
temp=first;
if (*temp=='\0') return NULL;
while (*temp!='\0' && ((*temp!=*delim) || comma))
{
if (*temp=='"') comma ^= 1;
temp++;
}
if (*temp=='\0') next=temp;
else
{
*temp='\0';
next=temp+1;
}
return first;
}
/*****************************************************************************/
/* Parses the csv file and return a list of stocks structure. */
/* *csv points on the csv file in memory */
/* count defines the country, because csv depends on the country */
/*****************************************************************************/
stock *parse_csv_file(char *csv)
{
char *line;
char *end_line;
char *ptr;
char *date;
char *time;
char *name;
char *symbol;
stock *StockPtr=NULL;
stock *LastStockPtr=NULL;
/* Used to return the pointer to the list */
stock *FirstStockPtr=NULL;
/* used to see if symbol is valid */
int valid;
char *test;
line = csv;
end_line = csv;
while ((end_line = strstr(line, "\n")))
{
*end_line = 0;
/* Check if symbol valid */
/* if 1 "N/A" then ok because Indices have N/A for volume */
/* if 4 "N/A" then ok because Mutual funds have */
/* if 5 "N/A" then ok because currencies have */
/* So if >5 then stock not valid */
test = line;
valid = 0;
while ( (test = strstr(test, "N/A")) )
{
valid ++;
test = test +3;
}
if (valid < 6)
{
/* This Symbol is valid */
StockPtr = malloc_stock();
ptr = csv_strtok(line, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ return 0;
+ }
symbol = (char *)malloc(strlen(ptr)+1);
if (symbol==NULL)
{
fprintf(stderr,"Memory allocating error (%s line %d)\n"
,__FILE__, __LINE__);
exit(1);
}
strcpy((char *)(symbol), ptr);
StockPtr->Symbol = symbol;
ptr = csv_strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ return 0;
+ }
name = (char *)malloc(strlen(ptr)+1);
if (name==NULL)
{
fprintf(stderr,"Memory allocating error (%s line %d)\n"
,__FILE__, __LINE__);
exit(1);
}
strcpy((char *)(name), ptr);
StockPtr->Name = name;
ptr = csv_strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ return 0;
+ }
sscanf(ptr,"%f",&(StockPtr->CurrentPrice));
ptr = csv_strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ return 0;
+ }
date = (char *)malloc(strlen(ptr)+1);
if (date==NULL)
{
fprintf(stderr,"Memory allocating error (%s line %d)\n"
,__FILE__, __LINE__);
exit(1);
}
strcpy((char *)(date), ptr);
StockPtr->Date = date;
ptr = csv_strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ return 0;
+ }
time = (char *)malloc(strlen(ptr)+1);
if (time==NULL)
{
fprintf(stderr,"Memory allocating error (%s line %d)\n"
,__FILE__, __LINE__);
exit(1);
}
strcpy((char *)(time), ptr);
StockPtr->Time = time;
ptr = csv_strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ return 0;
+ }
sscanf(ptr,"%f",&(StockPtr->Variation));
StockPtr->Pourcentage = 100 * StockPtr->Variation /
(StockPtr->CurrentPrice - StockPtr->Variation);
StockPtr->LastPrice = StockPtr->CurrentPrice - StockPtr->Variation;
ptr = csv_strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ return 0;
+ }
sscanf(ptr,"%f",&(StockPtr->OpenPrice));
ptr = csv_strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ return 0;
+ }
sscanf(ptr,"%f",&(StockPtr->MaxPrice));
ptr = csv_strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ return 0;
+ }
sscanf(ptr,"%f",&(StockPtr->MinPrice));
ptr = csv_strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ return 0;
+ }
StockPtr->Volume = atoi(ptr);
if( !FirstStockPtr )
{
FirstStockPtr = StockPtr;
StockPtr->PreviousStock = 0;
}
StockPtr->NextStock = 0;
if (LastStockPtr)
{
LastStockPtr->NextStock = StockPtr;
StockPtr->PreviousStock = LastStockPtr;
}
LastStockPtr = StockPtr;
}
else
{
/* this symbol is not valid */
/* Set the stock struct just with Symbol, all other are NULL */
/* This can be used to see if the symbol has been reached are not */
StockPtr = malloc_stock();
ptr = csv_strtok(line, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ return 0;
+ }
symbol = (char *)malloc(strlen(ptr)+1);
if (symbol==NULL)
{
fprintf(stderr,"Memory allocating error (%s line %d)\n"
,__FILE__, __LINE__);
exit(1);
}
strcpy((char *)(symbol), ptr);
StockPtr->Symbol = symbol;
if( !FirstStockPtr )
{
FirstStockPtr = StockPtr;
StockPtr->PreviousStock = 0;
}
StockPtr->NextStock = 0;
if (LastStockPtr)
{
LastStockPtr->NextStock = StockPtr;
StockPtr->PreviousStock = LastStockPtr;
}
LastStockPtr = StockPtr;
}
end_line++;
line = end_line;
}
return (FirstStockPtr);
}
/*****************************************************************************/
/* Parses the history quotes file and return a stock structure list. */
/*****************************************************************************/
stock *parse_csv_history_file(char *csv_file)
{
char *line;
char *end_line;
char *ptr;
int day;
char smonth[10];
int month;
int year;
char *date;
int i;
int test;
stock *StockPtr=NULL;
stock *LastStockPtr=NULL;
/* Used to return the pointer to the list */
stock *FirstStockPtr=NULL;
line = csv_file;
end_line = csv_file;
/* do not use the first line */
if (!(end_line = strstr(line, "\n")))
return 0;
*end_line = 0;
end_line++;
line = end_line;
while ((end_line = strstr(line, "\n")))
{
*end_line = 0;
StockPtr = malloc_stock();
/* Date */
ptr = strtok(line, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ free_stock(FirstStockPtr);
+ free_stock(LastStockPtr);
+ return 0;
+ }
sscanf(ptr,"%d-%3s-%d",&day,smonth,&year);
i=0;
#ifdef __UNIX__
while((test=strcasecmp(months[i], smonth))) i++;
#elif __WINDOWS__
while(test=_mbsnbicmp(months[i], smonth, strlen(months[i]))) i++;
#endif
month = i+1;
date = (char *)malloc(DATE_LENGTH);
if (date==NULL)
- {
- fprintf(stderr,"Memory allocating error (%s line %d)\n"
- ,__FILE__, __LINE__);
- exit(1);
- }
+ {
+ fprintf(stderr,"Memory allocating error (%s line %d)\n"
+ ,__FILE__, __LINE__);
+ exit(1);
+ }
sprintf(date,"%.2d%.2d%.2d", year, month, day);
StockPtr->Date = date;
/* Open */
ptr = strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ free_stock(FirstStockPtr);
+ free_stock(LastStockPtr);
+ return 0;
+ }
sscanf(ptr,"%f",&(StockPtr->OpenPrice));
/* High */
ptr = strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ free_stock(FirstStockPtr);
+ free_stock(LastStockPtr);
+ return 0;
+ }
sscanf(ptr,"%f",&(StockPtr->MaxPrice));
/* Low */
ptr = strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ free_stock(FirstStockPtr);
+ free_stock(LastStockPtr);
+ return 0;
+ }
sscanf(ptr,"%f",&(StockPtr->MinPrice));
/* Close */
ptr = strtok(NULL, ",");
- if (!ptr) return 0;
+ if (!ptr)
+ {
+ free_stock(StockPtr);
+ free_stock(FirstStockPtr);
+ free_stock(LastStockPtr);
+ return 0;
+ }
sscanf(ptr,"%f",&(StockPtr->LastPrice));
/* Volume */
ptr = strtok(NULL, ",");
if (!ptr)
- /* It seems to be an indice */
- /* No volume for indices */
- StockPtr->Volume = 0;
+ /* It seems to be an indice */
+ /* No volume for indices */
+ StockPtr->Volume = 0;
else
- StockPtr->Volume = atoi(ptr);
+ StockPtr->Volume = atoi(ptr);
if( !FirstStockPtr )
- {
- FirstStockPtr = StockPtr;
- StockPtr->PreviousStock = 0;
- }
+ {
+ FirstStockPtr = StockPtr;
+ StockPtr->PreviousStock = 0;
+ }
StockPtr->NextStock = 0;
if (LastStockPtr)
- {
- LastStockPtr->NextStock = StockPtr;
- StockPtr->PreviousStock = LastStockPtr;
- }
+ {
+ LastStockPtr->NextStock = StockPtr;
+ StockPtr->PreviousStock = LastStockPtr;
+ }
LastStockPtr = StockPtr;
end_line++;
line = end_line;
}
return (FirstStockPtr);
}
diff --git a/noncore/todayplugins/stockticker/libstocks/currency.c b/noncore/todayplugins/stockticker/libstocks/currency.c
index 9a08a9d..e0090e2 100644
--- a/noncore/todayplugins/stockticker/libstocks/currency.c
+++ b/noncore/todayplugins/stockticker/libstocks/currency.c
@@ -1,66 +1,67 @@
/* libstocks - Library to get current stock quotes from Yahoo Finance
*
* Copyright (C) 2000 Eric Laeuffer
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#define __CURRENCY_C__
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>
#include "stocks.h"
/*****************************************************************************/
/* returns the currency exchange rate of "from" currency into */
/* "into" currency. */
/*****************************************************************************/
libstocks_return_code get_currency_exchange(char *from,
char *into,
float *exchange)
{
char *symbol;
stock *data;
libstocks_return_code error;
if((symbol = (char *)malloc(strlen(from)+strlen(into)+3))==NULL)
{
fprintf(stderr,"Memory allocating error (%s line %d)\n"
,__FILE__, __LINE__);
exit(1);
}
strcpy(symbol, from);
strcat(symbol, into);
strcat(symbol, "=X");
error = get_stocks(symbol, &data);
+ free(symbol);
if (error)
{
*exchange = 0;
return(error);
}
free_stocks(data);
*exchange = data->CurrentPrice;
return(error);
}
diff --git a/noncore/todayplugins/stockticker/libstocks/lists.h b/noncore/todayplugins/stockticker/libstocks/lists.h
index 0132317..a0eb434 100644
--- a/noncore/todayplugins/stockticker/libstocks/lists.h
+++ b/noncore/todayplugins/stockticker/libstocks/lists.h
@@ -1,35 +1,36 @@
/* libstocks - Library to get current stock quotes from Yahoo Finance
*
* Copyright (C) 2000 Eric Laeuffer
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifndef __LISTS_H__
#define __LISTS_H__
#ifndef __LISTS_C__
#define PUBEXT_LISTS extern
#else
#define PUBEXT_LISTS
#endif
#include "stocks.h"
PUBEXT_LISTS stock *malloc_stock(void);
+PUBEXT_LISTS void free_stock(stock*);
#endif /* __LISTS_H */
diff --git a/noncore/todayplugins/stockticker/libstocks/stocks.c b/noncore/todayplugins/stockticker/libstocks/stocks.c
index eb04ba9..3a26a47 100644
--- a/noncore/todayplugins/stockticker/libstocks/stocks.c
+++ b/noncore/todayplugins/stockticker/libstocks/stocks.c
@@ -1,347 +1,348 @@
/* libstocks - Library to get current stock quotes from Yahoo Finance
*
* Copyright (C) 2000 Eric Laeuffer
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#define __STOCKS_C__
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>
#ifdef __WINDOWS__
#include <mbstring.h>
#endif
#include "http.h"
#include "csv.h"
#include "stocks.h"
/*
s = symbol
n = name
l1 = last trade
d1 = date
t1 = time
c1 = variation
o = open
h = higher price
g = lower price
v = volume
*/
const char yahoo_us_stocks_server[]="finance.yahoo.com";
const char yahoo_eu_stocks_server[]="finance.yahoo.com";
//const char yahoo_eu_stocks_server[]="fr.finance.yahoo.com";
const char yahoo_url_beg[]="/d/quotes.csv?s=";
const char yahoo_url_end[]="&f=snl1d1t1c1ohgv&e=.csv";
typedef enum {
YAHOO_EUROPE,
YAHOO_US
} yahoo_source;
#define YAHOO_US_EXT_NB 11
const char *yahoo_us_ext[YAHOO_US_EXT_NB] =
{
".US", /* United States */
".TO", /* Canada */
".M", /* Canada */
".V", /* Canada */
".AL", /* Canada */
".MX", /* Mexico */
".SA", /* Brasil */
".BA", /* Argentina */
".CR", /* Venezuela */
".SN", /* Chili */
".AX" /* Australia */
};
/*****************************************************************************/
/* Finds, according to the symbol extension, the http source of the quotes. */
/* Actually just finance.yahoo.com and fr.finance.yahoo.com are supported. */
/* The function returns the country source (US or EUROPE). */
/*****************************************************************************/
yahoo_source find_yahoo_source(char *symbol)
{
char *ptr;
int i;
int test;
ptr = strrchr(symbol, '.');
/* If no extension we suppose it is a US stock */
if (!ptr) return YAHOO_US;
/* extension is found */
/* Test if it is canadian stock */
for (i=0; i<YAHOO_US_EXT_NB; i++)
{
#ifdef __UNIX__
test = strcasecmp(yahoo_us_ext[i], ptr);
#elif __WINDOWS__
test = _mbsnbicmp(yahoo_us_ext[i], ptr, strlen(yahoo_us_ext[i]));
#endif
if (!test) return YAHOO_US;
}
-
+
/* We suppose now it is a European stock */
return YAHOO_EUROPE;
}
/*****************************************************************************/
/* Gets quotes csv file, parses the file and create the quotes list */
/* *stocks points to the stocks to fetch */
/* *stock_datas points to the beginning of the list */
/* count allows to connect to all country servers */
/*****************************************************************************/
-libstocks_return_code download_stocks(char *stocks,
- stock **stock_datas,
+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;
}
/*****************************************************************************/
/* Gets quotes from yahoo */
/* Choses to fetch European or US depending on the symbol extension */
/* and merges the two lists to one */
/* *stocks points to the stocks to fetch */
/* *stock_datas points to the beginning of the list */
/*****************************************************************************/
libstocks_return_code get_stocks(const char *stocks, stock **stock_datas)
{
char *tok_ptr;
char *eu_quotes=NULL;
char *eu_quotes_temp=NULL;
int lgr_eu_quotes=0;
char *us_quotes=NULL;
char *us_quotes_temp=NULL;
int lgr_us_quotes=0;
char *symbol;
yahoo_source source;
int lgr_symbol=0;
libstocks_return_code error;
stock *stocks_tmp=NULL;
stock *stocks_tmp2=NULL;
stock *stocks_getted=NULL;
stock *last_stock=NULL;
#ifdef DEBUG
printf("*get_stocks\n");
#endif
/* to preserve stocks */
tok_ptr = malloc(strlen(stocks)+1);
if(tok_ptr==NULL)
{
fprintf(stderr,"Memory allocating error (%s line %d)\n"
,__FILE__, __LINE__);
- exit(1);
+ exit(1);
}
strcpy(tok_ptr, stocks);
while( (symbol = strtok(tok_ptr, "+"))!=0)
{
/* clear tok_ptr for next strtok */
tok_ptr = NULL;
/* look for "." in the symbol */
source = find_yahoo_source(symbol);
switch (source)
- {
- case YAHOO_US:
-
- if (us_quotes)
- {
- lgr_us_quotes = strlen(us_quotes);
- lgr_symbol = strlen(symbol);
-
- us_quotes_temp = malloc(lgr_us_quotes + lgr_symbol +2);
- if(us_quotes_temp==NULL)
- {
- fprintf(stderr,"Memory allocating error (%s line %d)\n"
- ,__FILE__, __LINE__);
- exit(1);
- }
- strcpy(us_quotes_temp, us_quotes);
- strcat(us_quotes_temp,"+");
- strcat(us_quotes_temp,symbol);
-
- free(us_quotes);
- us_quotes = us_quotes_temp;
- }
- else
- {
- us_quotes = malloc(strlen(symbol)+1);
-
- if(us_quotes==NULL)
- {
- fprintf(stderr,"Memory allocating error (%s line %d)\n"
- ,__FILE__, __LINE__);
- exit(1);
- }
- strcpy(us_quotes, symbol);
- }
-
- break;
-
- case YAHOO_EUROPE:
-
- if (eu_quotes)
- {
- lgr_eu_quotes = strlen(eu_quotes);
- lgr_symbol = strlen(symbol);
-
- eu_quotes_temp = malloc(lgr_eu_quotes + lgr_symbol +2);
- if(eu_quotes_temp==NULL)
- {
- fprintf(stderr,"Memory allocating error (%s line %d)\n"
- ,__FILE__, __LINE__);
- exit(1);
- }
- strcpy(eu_quotes_temp, eu_quotes);
- strcat(eu_quotes_temp, "+");
- strcat(eu_quotes_temp, symbol);
-
- free(eu_quotes);
- eu_quotes = eu_quotes_temp;
- }
- else
- {
- eu_quotes = malloc(strlen(symbol)+1);
- if(eu_quotes==NULL)
- {
- fprintf(stderr,"Memory allocating error (%s line %d)\n"
- ,__FILE__, __LINE__);
- exit(1);
- }
- strcpy(eu_quotes, symbol);
- }
- break;
- }
+ {
+ case YAHOO_US:
+ if (us_quotes)
+ {
+ lgr_us_quotes = strlen(us_quotes);
+ lgr_symbol = strlen(symbol);
+
+ us_quotes_temp = malloc(lgr_us_quotes + lgr_symbol +2);
+ if(us_quotes_temp==NULL)
+ {
+ fprintf(stderr,"Memory allocating error (%s line %d)\n",
+ __FILE__, __LINE__);
+ exit(1);
+ }
+ strcpy(us_quotes_temp, us_quotes);
+ strcat(us_quotes_temp,"+");
+ strcat(us_quotes_temp,symbol);
+
+ free(us_quotes);
+ us_quotes = us_quotes_temp;
+ }
+ else
+ {
+ us_quotes = malloc(strlen(symbol)+1);
+
+ if(us_quotes==NULL)
+ {
+ fprintf(stderr,"Memory allocating error (%s line %d)\n",
+ __FILE__, __LINE__);
+ exit(1);
+ }
+ strcpy(us_quotes, symbol);
+ }
+
+ break;
+
+ case YAHOO_EUROPE:
+ if (eu_quotes)
+ {
+ lgr_eu_quotes = strlen(eu_quotes);
+ lgr_symbol = strlen(symbol);
+
+ eu_quotes_temp = malloc(lgr_eu_quotes + lgr_symbol +2);
+ if(eu_quotes_temp==NULL)
+ {
+ fprintf(stderr,"Memory allocating error (%s line %d)\n",
+ __FILE__, __LINE__);
+ exit(1);
+ }
+ strcpy(eu_quotes_temp, eu_quotes);
+ strcat(eu_quotes_temp, "+");
+ strcat(eu_quotes_temp, symbol);
+
+ free(eu_quotes);
+ eu_quotes = eu_quotes_temp;
+ }
+ else
+ {
+ eu_quotes = malloc(strlen(symbol)+1);
+ if(eu_quotes==NULL)
+ {
+ fprintf(stderr,"Memory allocating error (%s line %d)\n",
+ __FILE__, __LINE__);
+ exit(1);
+ }
+ strcpy(eu_quotes, symbol);
+ }
+ break;
+ }
}
free(tok_ptr);
if (us_quotes)
{
/* Gets us quotes */
error = download_stocks(us_quotes, &stocks_tmp, YAHOO_US);
+ free(us_quotes);
if (error) return error;
}
-
+
if (eu_quotes)
{
/* Gets european quotes */
error = download_stocks(eu_quotes, &stocks_getted, YAHOO_EUROPE);
+ free(eu_quotes);
if (error) return error;
/* concats lists if needed */
if (stocks_tmp)
- {
- stocks_tmp2 = stocks_tmp;
+ {
+ stocks_tmp2 = stocks_tmp;
- while(stocks_tmp2 != NULL)
- {
- last_stock = stocks_tmp2;
- stocks_tmp2 = next_stock(stocks_tmp2);
- }
+ while(stocks_tmp2 != NULL)
+ {
+ last_stock = stocks_tmp2;
+ stocks_tmp2 = next_stock(stocks_tmp2);
+ }
- last_stock->NextStock = stocks_getted;
- stocks_getted->PreviousStock = last_stock;
+ last_stock->NextStock = stocks_getted;
+ stocks_getted->PreviousStock = last_stock;
- }
- else (stocks_tmp = stocks_getted);
+ }
+ else
+ (stocks_tmp = stocks_getted);
}
- *stock_datas = stocks_tmp;
-
+ *stock_datas = stocks_tmp;
+
return(0);
}