From: Albert Wagner Date: 2001-11-05T05:23:39+09:00 Subject: [ruby-talk:24348] Re: Joys of eval On Sunday 04 November 2001 01:13 pm, you wrote: > On Sun, 2001-11-04 at 14:01, Albert Wagner wrote: > > On Sunday 04 November 2001 12:43 pm, you wrote: > > > and what happens when the string is > > > > > > '"abc",system("rm -rf ."),123' > > > > > > or something similar? > > > > It obviously will not work for ALL strings. I am only concerned with > > lines from a csv file, such as might be exported from MS Access. I do > > have a problem though: ', , ,' Empty fields cause eval to fail :-( > > the system command very well may be in a CSV file. You never know. Maybe I'm all wet, but CHAR data in a database is always put to a CSV file quoted, e.g. "abc", "system("rm -rf.")", 123 So that I don't think the string will be evaluated. Of course, someone may have manually diddled with it, removing the quotes and making it dangerous, but then technically it is no longer a CSV file. But you are right, $SAFE should be set for just that eventuality. > Trusting *anything* to eval without the SAFE level set up is very, very, > dangerous. Honestly, using eval at all is merely poor code design. > > The reason your problem was never solved well before was because regex > was depended on. Regex's can't do everything. And eval wil often do a > lot more than you want it to. > > The best bet is to scan the string character by character. Keep a > seperate string that you add each scanned character to. When you hit a > , copy the new string onto the end of your array. If you hit a \, then > set a temporary "escape" flag that makes the next character added to the > scan string no matter what (and then unset the escape flag). If you hit > a ", then set a quote mode that causes all scanned characters until the > next " to be added to the scan string. You can do the same with ', if > you want, but be sure to use a different escape flag, so ' won't > unescape a string started with ", and vice versa. Actually, such code already exists. I think that Robert Linder just added a module to the Cookbook. > Some string commands > will make the search much faster (find first occurance of '"\, ), since > they are run in C. This will be 100% robust if coded right (it will > even handle your above mentioned problem with ', , ,'), will likely be > faster than a regex (depending on regex engine), and will be perfectly > safe and sane, unlike a poor eval() implementation. > > Sean Etc.